#include #define ll long long using namespace std; int n, k; string s; ll mixed[33][123456]; ll pure[33][123456]; char type[33][123456]; bool que[33][123456]; int price[256]; int prime = 1, power = 0; void print() { for(int i = 0; i <= power; i++) { for(int j = 0; j < n; j++) cout << que[i][j] << " "; cout << endl; } cout << endl; for(int i = 0; i <= power; i++) { for(int j = 0; j < n; j++) cout << pure[i][j] << " "; cout << endl; } cout << endl; for(int i = 0; i <= power; i++) { for(int j = 0; j < n; j++) cout << mixed[i][j] << " "; cout << endl; } cout << endl; } int main() { ios::sync_with_stdio(false); cin.tie(NULL); cin >> n; cin >> s; cin >> k; char c; int a; ll ma = 0; char mac; for(int i = 0; i < k; i++) { cin >> c >> a; price[c] = a; if(a > ma) { ma = a; mac = c; } } for(int i = 2; i <= n; i++) { if(n % i == 0) { prime = i; int nn = n; while(nn > 1) { power++; nn /= i; } break; } } for(int i = 0; i < n; i++) { if(s[i] != '?') { type[0][i] = s[i]; pure[0][i] = price[s[i]]; mixed[0][i] = price[s[i]]; que[0][i] = false; } else { que[0][i] = true; mixed[0][i] = ma; } } int pw = prime; for(int e = 1; e <= power; e++) { for(int i = 0; i < n/pw; i++) { que[e][i] = true; mixed[e][i] = 0; bool types = false; for(int j = i; j < n; j += n/pw) { mixed[e][i] += mixed[e-1][j]; que[e][i] &= que[e-i][j]; if(type[e][i] && type[e-1][j] && type[e-1][j] != type[e][i]) { // cout << (int)type[e][i] << " " << (int)type[e-1][j] << endl; types = true; } else if(!type[e][i] && type[e-1][j]) { type[e][i] = type[e-1][j]; } } // cout << e << " " << i << " " << types << " " << type[e][i] << endl; if(!types) { if(type[e][i]) { pure[e][i] = (e + 1) * pw * price[type[e][i]]; } } else pure[e][i] = 0; mixed[e][i] = max(mixed[e][i], pure[e][i]); if(que[e][i]) mixed[e][i] = max(mixed[e][i], ma * pw * (e + 1)); } pw *= prime; } // print(); cout << mixed[power][0] << endl; return 0; }