# len of LC n = int(input().strip()) # owners s = input() # number of pizzo types k = int(input().strip()) # pizzo categories cc = {} # the best category best = "!" for i in range(k): c, v_str = input().strip().split() v = int(v_str) cc[c] = v if best == "!" or v > cc[best]: best = c # the prime p = 2 while(n % p != 0): p += 1 def log(x): power = 0 prod = 1 while(prod < x): power += 1 prod *= p return power def solve(step, offset): count = n // step pizzo = "?" for oi in range(offset, n, step): if s[oi] == pizzo or s[oi] == "?": continue elif s[oi] != "?" and pizzo == "?": pizzo = s[oi] else: pizzo = "#" if pizzo == "?": return count * cc[best] * (log(count) + 1) else: sumOfChildren = 0 if step < n: stepNew = step * p for i in range(p): sumOfChildren += solve(stepNew, offset + i * step) if pizzo == "#": return sumOfChildren else: return max(sumOfChildren, count * cc[pizzo] * (log(count) + 1)) print(solve(1, 0))