#include using namespace std; #define TRACE(x) cerr << __LINE__ << ": " << #x << " = " << x << endl #define _ << " _ " << template struct is_container : false_type {}; template struct is_container> : true_type {}; template struct is_container> : true_type {}; template struct is_container> : true_type {}; template struct is_container> : true_type {}; template struct is_container> : true_type {}; template struct is_container> : true_type {}; template struct is_container> : true_type {}; template::value>::type> ostream& operator<<(ostream &o, T x) { int f = 1; o << "{"; for (auto y : x) { o << (f ? "" : ", ") << y; f = 0; } return o << "}"; } template ostream& operator<<(ostream &o, pair x) { return o << "(" << x.first << ", " << x.second << ")"; } #define fi first #define se second typedef long long ll; typedef long double ld; typedef pair pii; typedef pair pll; typedef vector vi; typedef vector vll; const int K = 26; const ll INF = 1e18; vi a; vll cost(K); int n, p; vll solve(int mod_eq, int mod) { if (mod == n) { if (a[mod_eq] == -1) { auto dp = cost; dp.push_back(*max_element(dp.begin(), dp.end())); //TRACE(mod_eq _ mod _ dp[0] _ dp[1] _ dp.back()); return dp; } else { vll dp(K, -INF); dp[a[mod_eq]] = cost[a[mod_eq]]; dp.push_back(*max_element(dp.begin(), dp.end())); //TRACE(mod_eq _ mod _ dp[0] _ dp[1] _ dp.back()); return dp; } } vector ch_dp(p); for (int i = 0; i < p; i++) ch_dp[i] = solve(mod_eq + i * mod, mod * p); vll dp(K); for (int i = 0; i < K; i++) { for (auto& c : ch_dp) { if (dp[i] == -INF || c[i] == -INF) dp[i] = -INF; else dp[i] += c[i]; } if (dp[i] != -INF) dp[i] += cost[i] * (n / mod); } dp.push_back(0); for (auto& c : ch_dp) dp.back() += *max_element(c.begin(), c.end()); //TRACE(mod_eq _ mod _ dp[0] _ dp[1] _ dp.back()); return dp; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cin >> n; if (n == 1) p = 1; else { p = 2; while (n % p != 0) p++; } a.resize(n); string s; cin >> s; for (int i = 0; i < n; i++) { if (s[i] == '?') a[i] = -1; else a[i] = s[i] - 'A'; } int k; cin >> k; for (int i = 0; i < k; i++) { char c; int v; cin >> c >> v; assert(cost[c - 'A'] == 0); cost[c - 'A'] = v; } vll dp = solve(0, 1); cout << *max_element(dp.begin(), dp.end()) << '\n'; return 0; }