Crabbles

Time limit1sMemory limit128 MB

Summary
Given a dictionary and hands of at most 10 lettered tiles with values, find the maximum-scoring dictionary word formable from each hand's tiles.
Level

Medium7 of 10

Topics
Trie, Backtracking, Implementation, Array
Solved
No attempts yet

Problem

Jennifer is practicing for a Crabbles tournament. She pulls a handful of Crabbles tiles out of a bag and tries to form the word with the highest possible score. Each tile shows a letter (used to form the word) and a number (its score value). She may use each tile at most once in her word, and she does not have to use every tile. The word she forms must appear in her dictionary. Her score is the sum of the values of the tiles used in the word.

Note that in Crabbles, different tiles showing the same letter may have different score values.

To check her work, Jennifer would like a program that reports the maximum score possible for a given set of tiles. Your task is to write this program.

Input

The first line contains an integer NN (1≤N≤100,0001 \le N \le 100{,}000), the number of words in the dictionary. The next NN lines each contain one dictionary word, consisting only of lowercase letters. The following line contains an integer MM (1≤M≤1,0001 \le M \le 1{,}000), the number of Crabbles hands Jennifer wants to play. The MM hands follow. Each hand begins with a line containing an integer PP (1≤P≤101 \le P \le 10), the number of tiles in the hand, followed by PP lines, one per tile. Each such line contains a lowercase letter (the letter on the tile), a space, and an integer VV (0≤V≤100 \le V \le 10), the value of the tile.

Output

For each hand, output a single line containing the maximum score possible with that hand. If no dictionary word can be formed, output 00.

Examples1

  1. Example 1

    Input
    2
    abcd
    hgfe
    1
    10
    a 1
    b 2
    c 3
    d 4
    e 5
    f 6
    g 7
    h 8
    i 9
    j 10
    
    Expected output
    26