#include using namespace std; using LL = long long; #define FOR(i, l, r) for(int i = (l); i <= (r); ++i) #define REP(i, n) FOR(i, 0, (n) - 1) #define ssize(x) int(x.size()) template auto& operator<<(ostream &o, pair p) { return o << '(' << p.first << ", " << p.second << ')'; } template auto operator<<(ostream &o, T x) -> decltype(x.end(), o) { o << '{'; int i = 0; for(auto e : x) o << (", ")+2*!i++ << e; return o << '}'; } #ifdef DEBUG #define debug(x...) cerr << "[" #x "]: ", [](auto... $) {((cerr << $ << "; "), ...); }(x), cerr << '\n' #else #define debug(...) {} #endif const int ALPH = 26; int main() { ios_base::sync_with_stdio(0); cin.tie(0); int n, k; char ch; string s; cin >> n >> s >> k; vector val(ALPH); REP(i, k) { cin >> ch; cin >> val[ch - 'A']; } int prime = 1; FOR(i, 2, n) { if (n % i == 0) { prime = i; break; } } int cnt = 1, pwr = 1; LL ans = 0; while (pwr != n) { pwr *= prime; cnt++; } int jump = 1, sign; vector > dp(n); REP(i, n) dp[i].resize(ALPH); REP(i, cnt) { REP(j, n) { sign = s[j] - 'A'; if (s[j] == '?') { REP(l, ALPH) dp[j][l] = val[l]; if (j >= jump) { REP(l, ALPH) dp[j][l] += dp[j - jump][l]; } } else { dp[j][sign] = val[sign]; if (j >= jump) dp[j][sign] += dp[j - jump][sign]; } } LL now = 0, mx; REP(j, jump) { mx = 0; REP(l, ALPH) mx = max(mx, dp[n - j - 1][l]); now += mx; } ans = max(ans, now * (LL) (cnt - i)); jump *= prime; REP(j, n) fill(dp[j].begin(), dp[j].end(), 0); } cout << ans << '\n'; return 0; }