Decompressing in a GIF#1188

Decompressing in a GIF

1 second
32 megabytes
Medium

One well-known method to compress image files is the Graphics Interchange Format (GIF) encoding, created by CompuServe in . Here's a simplified version applied to strings of alphabetic characters. Essential for this compression is a dictionary which assigns numeric encodings (we'll use base numbers for this problem) to different strings of characters. The dictionary is initialized with mappings for characters or substrings which may appear in the string. For example, if we expect to encounter all letters of the alphabet, the dictionary will initially store the encodings , , , , . If we are compressing DNA data, the dictionary will initially store only entries: , , , and . Note that the length of each initial encoding is the same for all entries ( digits in the first example, and digit in the second).

The compression algorithm proceeds as follows:

  1. Find the longest prefix of the uncompressed portion of the string which is in the dictionary, and replace it with its numeric encoding.

  2. If the end of the string has not been reached, add a new mapping to the dictionary, where is the prefix just compressed plus the next character in the string, and is the smallest number not yet used in the dictionary.

For example, assume we started with the string ABABBAABB and a dictionary with just two entries, and . The table below shows the steps in compressing the string.

The final compressed string is .

There is only one other rule: the replacement strings are always of the same length as the longest encoding in the dictionary at the time the replacement occurs. Thus, with the dictionary above, if the string to compress is long enough that an entry of the form is added to the dictionary, then from this point on, all numerical replacement strings used in the compressed string must be expanded to digits (i.e., will now be encoded as , as , as , etc.); if an entry (s', 100) is added to the dictionary, all replacements from this point forward will increase to digits long, and so on. Thus, the longer string ABABBAABBAABAABAB will be encoded as , not .

OK, now that you are experts at compressing, it's time to relax and decompress!

Input

Each test case will consist of two lines. The first line will contain a string of digits to decompress. The second line will contain the initial dictionary used in the compression. This line will start with a positive integer indicating the number of entries in the dictionary (1 \le n \le 100), followed by alphabetic strings. The first of these will be paired with in the dictionary (or if n > 10), the second with , and so on. The last test case will be followed by a line containing a single .

Output

For each test case, output a single line containing the case number (using the format shown below) followed by the decompressed string. All input strings will have been legally compressed.

Examples

Example 1

Loading
Loading