#include <bits/stdc++.h>
using namespace std;
#define FOR(i, a, b) for(int i = (a); i < (b); i++)
#define RFOR(i, a, b) for(int i = (a) - 1; i >= (b); i--)
#define SZ(a) int(a.size())
#define ALL(a) a.begin(), a.end()
#define PB push_back
#define MP make_pair
#define F first
#define S second
typedef long long LL;
typedef vector<int> VI;
typedef pair<int, int> PII;
typedef double db;
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
string s;
cin >> s;
map<char, int> value;
int k;
cin >> k;
char mx = '0';
FOR(i, 0, k)
{
char x;
cin >> x;
int val;
cin >> val;
value[x] = val;
if(mx == '0' || val > value[mx])
mx = x;
}
int m = n;
int p = -1;
for(int pr = 2; pr * pr <= n; pr++)
{
if(n % pr)
continue;
p = pr;
n = 1;
break;
}
if(n != 1)
p = n;
assert(p != -1);
n = m;
int beta = 0;
int pw = 1;
while(pw < n)
{
beta++;
pw *= p;
}
vector<LL> dp(n);
int pwU = p;
RFOR(alpha, beta + 1, 0)
{
vector<LL> ndp(pw);
FOR(ost, 0, pw)
{
VI cnt(26, 0);
int pos = ost;
while(pos != ost)
{
if(s[pos] != '?')
cnt[s[pos] - 'A']++;
pos += pw;
if(pos >= n)
pos -= n;
}
LL cur = 0;
int num = 0;
FOR(i, 0, 26)
{
if(cnt[i] != 0)
{
cur = value[char('A' + i)];
num++;
}
}
if(num == 0)
cur = value[mx];
if(num >= 2)
cur = 0;
ndp[ost] = cur * (pwU - 1) / (p - 1);
cout << pw << " " << ost << " " << ndp[ost] << "\n";
if(alpha != beta)
{
LL sum = 0;
FOR(i, 0, p)
{
sum += dp[pw * i + ost];
}
ndp[ost] = max(ndp[ost], sum);
}
}
dp = ndp;
pw /= p;
pwU *= p;
}
cout << dp[0] << "\n";
return 0;
}
4 0 25
4 1 25
4 2 25
4 3 25
2 0 75
2 1 75
1 0 175
175