Assembly line#1826

Assembly line

10 seconds
256 megabytes
Very easy

The last worker in a production line at the factory of Automated Composed Machinery is worried. She knows that her job hangs in the balance unless her productivity increases. Her work consists of assembling a set of pieces in a given sequence, but the time spent assembling pieces and , then , may not be the same as assembling and and then with the resulting component. Only two consecutive pieces can be assembled at a time, and once assembled they behave as another piece in terms of the time needed for further assembly.

To aid her, you need to find the optimal way to assemble all components. The input to your program will be a set of symbols representing types of pieces, and an assembly table indicating the time it takes to assemble them, as well as the type of the resulting component. For instance, we may have two symbols and the following table:

This means, for example, that two pieces of type and may be assembled in minutes, and the result is a component of type , so that the time required to assemble it again with another piece of, say, type is minutes, and so on. Note that the table is not symmetric, i.e., assembling and may be more time-consuming than and .

For a sequence of components labeled , the two possible solutions are:

So the result for this case would be a piece of type in minutes (denoted ).

Input

The input consists of several test cases. Each test case begins with a line containing a natural number (1 \leq k \leq 26), followed by a line with symbols (characters in [a-z]) separated by spaces. The following lines contain the assembly table: the -th line has pairs of the form , where is an integer between and inclusive, and is a symbol belonging to the preceding set. The -th pair in the -th line represents the time to compose pieces of the types represented by the -th and -th symbols, and the type of the resulting piece. After the table, a line with an integer indicates the number of lines that follow, each line being a string of at most symbols. Each of these lines is a sequence of components that must be assembled together in the right order.

The input will finish with a line containing '0', which should not be processed.

Output

For each test case, print lines, each with an integer time and a symbol result in the format . Each line represents the minimum time and the type of the resulting piece for the corresponding case in the input. In case of a tie among several possible results with the same minimum time, choose the piece whose type letter appears first in the line containing the symbols at the beginning of the test case. (For example, if that line was and both and can be obtained with minimum cost , print ).

There must be an empty line between the outputs of different test cases.

Examples

Example 1

Loading
Loading