#include using namespace std; const int maxn = 1e5+1; typedef long long ll; int main() { ll N, val[26], type[maxn], profit[maxn], ln = 0; bool fix[maxn]; // input and values cin>> N; char ch; for (int i = 0; i < N; ++i) { cin>> ch; if (ch == '?') { type[i] = -1; fix[i] = false; } else { type[i] = int(ch-'A'); fix[i] = true; } } for (int i = 0; i < 26; ++i) val[i] = 0; int M; cin>> M; for (int i = 0 ; i < M; ++i) { cin>> ch; cin>> val[int(ch-'A')]; } for (int i = 1; i < 26; ++i) if (val[i] > val[ln]) ln = i; // fill values for (int i = 0; i < N ; ++i) { if (type[i] == -1) { type[i] = ln; } profit[i] = val[type[i]]; } // p ll p = 2; for (ll i=2; i<=N; ++i) { if (N % i == 0) { p = i; break; } } //merge for (ll d = N/p, divnum = 1; d > 0; d/=p, divnum++) { for (int i = 0; i < d; ++i) { // every shift int fixType = -1; bool fixTypeFail = false; ll profitsum = 0; for (int j = i; j < d*p; j+=d) { // after every step profitsum += profit[j]; if (fix[j]) { if (fixType == -1) { fixType = type[j]; if (fixType == -1) fixTypeFail = true; } else { if (type[j] != fixType) fixTypeFail = true; } } } if (fixTypeFail) { fix[i] = true; type[i] = -1; profit[i] = profitsum; } else if (fixType == -1) { type[i] = ln; profit[i] = (N/d)*val[ln]*(divnum+1); } else { fix[i] = true; type[i] = fixType; profit[i] = max(profitsum, (N/d)*val[fixType]*(divnum+1)); } } } cout<< profit[0] <