Generic Units Conversion

Time limit1sMemory limit128 MB

Problem

Design a program that reads the description of two systems of measurement for a common physical quantity (length, weight, area, time, and so on), a rule that converts between the two systems, and a quantity expressed in the first system, and then expresses that same quantity in the second system.

Input

The input contains one or more problem sets. Each problem set describes two systems of measurement, one conversion rule between them, and a list of quantities to convert.

Each problem set has the following structure.

  1. A line naming the units of the first system, from the largest unit to the smallest, separated by single spaces. This line is at most 80 characters long. Each unit name consists only of alphabetic characters, and no name is repeated on the line.
  2. If the first system has $N$ units, the next $N-1$ lines give internal conversion rules in the form a unit1 = b unit2, where $a$ and $b$ are positive numbers (integer or decimal) and unit1, unit2 are units of the first system. These $N-1$ rules always provide enough information to convert between any two units of the system.
  3. The second system is described immediately afterward in the same format (its unit line followed by its $N-1$ internal rules).
  4. One conversion rule in the same a unit1 = b unit2 form, where unit1 belongs to the first system and unit2 belongs to the second system.
  5. One or more quantity lines follow. A quantity is written as one or more (number, unit) pairs; within a quantity the units appear in decreasing order of size, though not every unit of the system need appear. Every number is non-negative.

A completely empty line marks the end of the list of quantities and of that problem set. If the line after that empty line is non-empty, another problem set begins; if it is also empty, the input ends.

All values stay within ranges for which every output number fits in a normal (32-bit) integer.

Output

For each quantity, print one line giving the equivalent quantity in the second system. List every unit of the second system, from largest to smallest, including any unit whose count is zero. Choose the counts greedily so that the larger units absorb as much of the value as possible. Every count is an integer, and the count of the smallest unit is rounded to the nearest integer (exact halves round up). Separate every number and unit name by a single space.