#pragma ide diagnostic ignored "misc-no-recursion"
#include "bits/stdc++.h"
using namespace std;
typedef long long ll;
typedef double db;
#define TESTCASE 0
static constexpr ll INF = 1e11;
static array<ll, 27> f(int d, int o, int p, const string &S, const array<ll, 27> &V) {
if (d == S.size()) {
if (S[o] == '?') return V;
array<ll, 27> res{};
res.fill(-INF);
res[S[o] - 'A'] = V[S[o] - 'A'];
return res;
}
array<ll, 27> res{};
for (int i = 0; i < 26; i++) {
res[i] += V[i] * (ll)S.size() / d;
}
for (int i = 0; i < p; i++) {
auto rec = f(p * d, o + d * i, p, S, V);
for (int j = 0; j < 27; j++) {
res[j] += rec[j];
}
}
res.back() = *max_element(res.begin(), res.end());
return res;
}
static void solve([[maybe_unused]] int tc) {
int N, K;
string S;
cin >> N >> S >> K;
array<ll, 27> V{};
V.fill(-INF);
for (int i = 0; i < K; i++) {
char c;
int x;
cin >> c >> x;
V[c - 'A'] = x;
}
V.back() = *max_element(V.begin(), V.end());
print("V =", V);
int p = N;
for (int i = 2; i < N; i++) {
if (N % i == 0) {
p = i;
break;
}
}
cout << f(1, 0, p, S, V).back() << endl;
}
int main() {
ios::sync_with_stdio(false);
if (const char *f = getenv("REDIRECT_STDOUT"); f) {
freopen(f, "w", stdout);
}
int T = 1;
#if TESTCASE
cin >> T;
#endif
for (int t = 1; t <= T; t++) {
solve(t);
}
return 0;
}