#include #define FOR(i, n) for(int i = 0; i < (n); ++i) #define REP(i, a, b) for(int i = (a); i < (b); ++i) #define TRAV(i, a) for(auto & i : (a)) #define SZ(x) ((int)(x).size()) #define X first #define Y second #define PR std::pair #define MP std::make_pair typedef long long ll; typedef std::pair PII; typedef std::vector VI; int cost[266]; std::vector chars; int BEST; ll rec(std::string s, int p, int ile); ll podziel(std::string s, int p, int ile){ ll ret = 0; FOR(kt, p){ std::string heh; for(int i = kt; i < SZ(s); i += p){ heh += s[i]; } ret += rec(heh, p, ile-1); } return ret; } ll rec(std::string s, int p, int ile){ char moj = s[0]; bool bad = false; TRAV(c, s){ if(c != '?' && c != moj){ bad = true; } } // std::cout << "rec " << s << " " << p << " " << ile << std::endl; if(bad) return podziel(s, p, ile); ll cand = 0; if(ile > 1){ cand = podziel(s, p, ile); } if(moj == '?'){ // std::cout << "ret " << std::max(cand, 1ll * BEST * SZ(s) * ile) << std::endl; return std::max(cand, 1ll * BEST * SZ(s) * ile); }else{ // std::cout << "ret " << std::max(cand, 1ll * cost[moj] * SZ(s) * ile) << std::endl; return std::max(cand, 1ll * cost[moj] * SZ(s) * ile); } } int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(0); int n; std::cin >> n; std::string s; std::cin >> s; int k; std::cin >> k; FOR(i, k){ char a; int b; std::cin >> a >> b; chars.push_back(a); cost[a] = b; BEST = std::max(BEST, b); } int p = 1; REP(i, 2, n+1){ if(n % i == 0){ p = i; break; } } int ile = 1; int cp = n; while(cp != 1){ cp /= p; ile++; } std::cout << rec(s, p, ile) << "\n"; return 0; }