import sys
from itertools import product


sys.stdin.readline()
retezec = sys.stdin.readline()
sys.stdin.readline()
ceny = {}
for l in sys.stdin:
  c,p = l.split()
  ceny[c] = int(p)
max_sum = 0
m = 0

def is_valid(kolecko, r):
  c = r[kolecko[0]]
  for idx in kolecko:
    if r[idx] != c:
      return False
  return True

def najdi_nejvetsi(kolecka):
  global ceny
  max_sum = 0
  for (r, k) in kolecka.items():
    s = 0
    for kolecko in k:
      s+=sum([ceny[r[idx]] for idx in kolecko])
    max_sum = max(s,max_sum)
  return max_sum

def nahrad_retezec(r, comb):
  for c in comb:
    r = r.replace("?", c, 1)
  return r



def najdi_kolecka(r, comb):
  kolecka = {}
  global max_sum 
  
  x = nahrad_retezec(r, comb)
  kolecka[x]= [[i] for i in range(0, len(x))]
  for ch in x:
    sum = 0
    for d in range(1, int(len(r)/2)+1):
      if len(r) % d == 0:
        for start in range(0, d):
          kolecko = []
          idx = start
          kolecko.append(idx)
          idx = (idx + d) % len(r)
          while idx != start:
            kolecko.append(idx)
            idx = (idx + d) % len(r)
          if is_valid(kolecko, x):
            if x not in kolecka:
              kolecka[x] = []
            if kolecko not in kolecka[x]:
              kolecka[x].append(kolecko)
    return kolecka

def merge_two_dicts(x, y):
    z = x.copy()   # start with keys and values of x
    z.update(y)    # modifies z with keys and values of y
    return z

def combinations(li, l):
  # li = ['a', 'b', 'c']
  c = []
  for comb in product(li, repeat=l):
    # print(''.join(comb))
    c.append(comb)
  return c

l = retezec.count('?')
comb = combinations(ceny.keys(), l)

kolecka = {}
for c in comb:
  kolecka = merge_two_dicts(kolecka, najdi_kolecka(retezec[:-1], c))

print(najdi_nejvetsi(kolecka))
