#include<bits/stdc++.h>
using namespace std;
int a,jmp=1,ile, maks_value;
int tab[100005];
int values[105];
long long out = 0;
long long rek(int start, int cur_jmp, int pot)
{
    set<int> s;
    if(tab[start] != 0)
        s.insert(tab[start]);
    for(int x = (start + cur_jmp) % a ; x != start ; x = (x + cur_jmp) % a )
        if(tab[x] != 0)
            s.insert(tab[x]);
    long long res = 0;
    if(s.size() == 0)
        res = (long long)a/cur_jmp*maks_value*(ile-pot+1);
    else if(s.size() == 1)
        res = (long long)a/cur_jmp*(values[*s.begin()])*(ile-pot+1);
    //cout<<start<<" "<<cur_jmp<<" "<<pot<<" "<<res<<" "<<s.size()<<'\n';
    if(cur_jmp == a)
        return res;
    long long res2 = 0;
    res2 += rek(start, cur_jmp * jmp, pot + 1);
    for(int x = (start + cur_jmp) % a ; x != (start + cur_jmp * jmp) % a ; x = (x + cur_jmp) % a )
        res2 += rek(x, cur_jmp * jmp, pot + 1);
    return max(res, res2);

}
int main()
{
	ios_base::sync_with_stdio(0);
	cin.tie(0);
    cin>>a;
    for(int x=2;x<=a;x++)
        if(a%x==0)
        {
            jmp = x;
            break;
        }
    string d;
    cin>>d;
    for(int x=0;x<a;x++)
    {
        tab[x] = (d[x] - 'A') + 1;
        if(d[x] == '?')
            tab[x] = 0;
    }

    int pom = a;
    while(pom != 1)
    {
        pom/=jmp;
        ile++;
    }
    int b;
    cin>>b;
    for(int x=0;x<b;x++)
    {
        char e;
        int f;
        cin>>e>>f;
        values[(e-'A') + 1] = f;
        maks_value = max(maks_value, f);
    }
    cout<<rek(0, 1, 0);

	return 0;
}
