/*{{{*/ #include #ifdef LOCAL int c_ = 0; #define cout (c_?cerr:cout) #define debug(...) \ {if(!c_++)cerr<<"\033[96;1m"; \ __VA_ARGS__; \ if(!--c_)cerr<<"\033[0m";} #else #define debug(...) {} #endif #define assrt(...) debug(\ if (not (__VA_ARGS__)) \ exit((cerr << __LINE__ << ": " << #__VA_ARGS__ << '\n', 0));\ ) #define st first #define nd second #define all(...) (__VA_ARGS__).begin(), (__VA_ARGS__).end() using namespace std; using ll = long long; using ld = long double; template < typename t > using V = vector< t >; template < typename t, size_t s > using A = array< t, s >; void print() {cout << '\n';} template< typename t, typename... v > void print(const t& a, const v&... b) {cout << a << (sizeof...(b)?" ":""); print(b...);} template< typename t > void print_range(t a, const t& b) { while (a != b) cout << (*a++) << ' '; cout << '\n';} #define dump(...) debug(print(#__VA_ARGS__,'=',__VA_ARGS__)) #define dump_range(...) debug(cerr<<#__VA_ARGS__ << ": "; print_range(__VA_ARGS__)) /*}}}*/ constexpr int nax = 1e5; int n, k, p = 2, m, val[26], mks; string s; ll dp(const int r, const int d, const int u) { int a = -1; int i = u; do { if (s[i] != '?') { if ((int)(s[i] - 'A') != a) { if (a == -1) { a = (int)(s[i] - 'A'); } else { a = 26; } } } i += d; if (i >= n) i -= n; } while (i != u); dump(r, d, u, a); ll res = 0; if (a != 26) { if (a != -1) { res = max(res, (ll)(m - r + 1) * (ll)val[a] * (n / d)); } else { res = max(res, (ll)(m - r + 1) * (ll)mks * (n / d)); } } if (p != 1 and d * p <= n) { ll tmp = 0; for (int i = 0; i < p; ++i) { tmp += dp(r + 1, d * p, i * d); } res = max(res, tmp); } return res; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cin >> n; cin >> s; cin >> k; for (int i = 0; i < k; ++i) { char c; int v; cin >> c >> v; val[c - 'A'] = v; mks = max(v, mks); } if (n == 1) { p = 1; } while ((n % p) != 0) { ++p; } int tmp = n; while (p != 1 and ((tmp % p) == 0)) { tmp /= p; ++m; } if (n == 1) { m = 0; } dump(p); dump(m); dump(n); cout << dp(0, 1, 0) << '\n'; }