#include #include #include #include #pragma GCC optimize("O3") #pragma GCC target("sse4") #pragma GCC target("avx2") #define deb(x) cout << #x << " = " << x << "\n" #define all(x) (x).begin(), (x).end() #define len(x) (ll) x.size() #define lsb(x) (x) & -(x) #define l(x) (x << 1) + 1 #define r(x) (x << 1) + 2 #define v(x) (ll)(x - 'a') #define xx first #define yy second #define mp make_pair #define pb push_back #define lb lower_bound #define ub upper_bound using namespace std; using namespace __gnu_pbds; typedef long long ll; typedef long double ld; typedef pair pii; typedef pair pld; typedef pair pll; template > using pb_heap = __gnu_pbds::priority_queue ; template > using pb_map = tree ; template > using pb_umap = gp_hash_table ; template > using umap = unordered_map ; template using uset = unordered_set ; template using vec = vector ; const ll infll = numeric_limits ::max() >> 1; const ll inf = numeric_limits ::max() >> 1; const ll N = 1e5 + 1; const ll L = 20; ll n, p, k, mxval, dp[L][N], value[256]; string t; void input() { cin >> n; cin >> t; cin >> k; for (ll i = 2; i <= n; ++i) { if (n % i == 0) { p = i; break; } } for (ll i = 0; i < k; ++i) { char chr; ll val; cin >> chr >> val; mxval = max(mxval, val); value[chr] = val; } value['?'] = mxval; } void solve() { if (n == 1) { cout << value[t[0]] << "\n"; return; } ll c = 0; for (ll i = 1; i < n; i *= p) { c++; } for (ll i = c, d = n; i >= 0; --i, d /= p) { for (ll pos = 0; pos < d; ++pos) { bool allsame = true; char prevchar = t[pos]; for (ll cur = pos; cur < n; cur += d) { if (t[cur] == '?') { continue; } if (prevchar == '?') { prevchar = t[cur]; } allsame &= t[cur] == prevchar; } if (i != c) { for (ll nxt = pos, j = 0; j < p; ++j, nxt += d) { dp[i][pos] += dp[i + 1][nxt]; } } if (allsame) { dp[i][pos] = max(dp[i][pos], value[prevchar] * n / d * (c - i + 1)); } } } cout << dp[0][0] << "\n"; } int main() { ios_base::sync_with_stdio(false); cin.tie(0), cout.tie(0); input(); solve(); }