This page is still under construction.

Parts of this page are still being built. What you see may change.

Scribble

Interview

Time limit1sMemory limit128 MB

Summary
Given seven tiles with letter values and a dictionary of up to 100000 words, find the highest-scoring dictionary word formable from the tiles, or 0 if none is.
Level

Medium5 of 10

Topics
String, Hash map, Brute force, Implementation
Solved
No attempts yet

Problem

Nixed, he placed the flong into the calathi halfway through the yuga.

Huh?

Believe it or not, the sentence above is a perfectly valid English sentence. It also has two other qualities: it looks like spam, and its words are very valuable.

Valuable, you say? (For some reason, you keep talking to yourself today.)

Yes — valuable, if you are playing Scribble. In the standard game of Scribble, calathi ("a vase-shaped basket depicted in Greek painting and sculpture") is worth 7272 points, nixed ("refused") is worth 2626 points, flong ("a compressed mass of paper sheets forming a matrix or mold for stereotype plates") is worth 1818 points, and yuga ("any one of the four ages — Krita or Satya, Treta, Dwapara, and Kali — into which Hindu tradition divides the existence of the world") is worth 3333 points.

As you may know, each letter in Scribble is worth a fixed number of points, and the goal is to score as many points as possible from a given set of letters.

For this problem we change the rules slightly. You have 77 tiles (letters), and each letter α\alpha has a score sαs_\alpha with 0≤sα≤260 \le s_\alpha \le 26. Before you play, you may also consult a dictionary of valid words (unlike normal Scribble). Your task is to find the highest-scoring word you can form. The score of a word is the sum of the scores of its letters.

Input

The first line contains an integer kk (1≤k≤71 \le k \le 7). Each of the next kk lines contains a triple α sα rα\alpha\ s_\alpha\ r_\alpha, where α\alpha is a letter, sαs_\alpha is that letter's score, and rαr_\alpha is the number of tiles bearing that letter. You may assume ∑αrα=7\sum_\alpha r_\alpha = 7. For example, the triple a 7 2 means you have two a tiles, each worth 77 points. The next line (line k+2k+2) contains an integer NN (0≤N≤100 0000 \le N \le 100\,000). Each of the following NN lines contains one word (each word has length at least one).

Output

Output a single line containing one integer: the maximum score — the greatest number of points obtainable by using your tiles to form one complete word from the dictionary. If no word can be formed, output 00.

Examples1

  1. Example 1

    Input
    4
    a 1 1
    b 4 1
    c 2 1
    d 10 4
    3
    ab
    bc
    c
    
    Expected output
    6