#include #include #include using namespace std; using namespace __gnu_pbds; #define ll long long #define lll __int128 #define ull unsigned long long #define fi first #define se second #define db double #define ld long double #define lld __float128 /// order_of_key, find_by_order template using custom_set = tree; template using ordered_set = tree, rb_tree_tag, tree_order_statistics_node_update>; template using ordered_multiset = tree, rb_tree_tag, tree_order_statistics_node_update>; template using ordered_map = tree, rb_tree_tag, tree_order_statistics_node_update>; mt19937 rnd(chrono::steady_clock::now().time_since_epoch().count()); mt19937_64 rnd_64(chrono::steady_clock::now().time_since_epoch().count()); ll cst[27], mx; vector ctg; ll dvd, pw; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n; cin >> n; for(int i = 2; i <= n; i++) { if(n % i == 0) { dvd = i; break; } } int N = n; while(N > 1) { pw++; N /= dvd; } string s; cin >> s; int k; cin >> k; for(int i = 0; i < k; i++) { char c; cin >> c; ctg.push_back(c); cin >> cst[c-'A']; mx = max(mx, cst[c-'A']); } ll ans = 0, vl = 1; for(int i = 0; i <= pw; i++) { ll res = 0; for(int st = 0; st < vl; st++) { bool good = 1; char c = '#'; for(int j = st; j < n; j += vl) { if(s[j] != '?') { if(c == '#') c = s[j]; else if(c != s[j]) { good = 0; break; } } } if(!good) continue; if(c != '#') { res += (pw-i+1) * cst[c-'A']*n/vl; } else { res += (pw-i+1) * mx*n/vl; } } ans = max(ans, res); vl *= dvd; // cout << ans; } cout << ans; } /// shche ne vmerla Ykraina