#include using namespace std; #ifdef DEB #define D if(1) #else #define D if(0) #endif #define fo(a,b) for(int a=0;a<(b);++a) using ll = long long; const int KMAX = 30; const int NMAX = 212345; int n, k; ll money[KMAX]; char in[NMAX]; ll dp[NMAX][KMAX]; #define NOPE (-(1ll<<40)) void prline(int i) { fo(x,KMAX) printf(dp[i][x]<0?" N":" %3lld", dp[i][x]); printf("\n"); } int main(int argc, char ** argv) { scanf("%d %s",&n,in); scanf("%d",&k); fo(i,k) { char c; ll val; scanf(" %c %lld", &c, &val); money[c-'A'+1]=val; } fo(i,n) in[i] = in[i]=='?'?0:in[i]-'A'+1; int p; for(p=2;n%p;p++); fo(i,n) { fo(x,KMAX) if(!in[i] || in[i]==x) dp[i][x]=money[x]; else dp[i][x]=NOPE; fo(x,KMAX) dp[i][0] = max(dp[i][0], dp[i][x]); D prline(i); } int start = n; int old_start = 0; int jump = n/p; int count = p; for(;jump; jump/=p, count*=p) { D printf("-----------------\n"); fo(i, jump) { fo(x, KMAX) fo(j,p) dp[start+i][x] += dp[old_start+i+j*jump][x]; fo(x, KMAX) if(x) dp[start+i][x] += count*money[x]; fo(x,KMAX) dp[start+i][0] = max(dp[start+i][0], dp[start+i][x]); fo(x,KMAX) if(dp[start+i][x] < 0) dp[start+i][x] = NOPE; D prline(start+i); } old_start = start; start+= jump; } printf("%lld\n",dp[old_start][0]); return 0; }