Generic Units Conversion
Time limit1sMemory limit128 MB
Parse two measurement systems with internal conversion rules, then convert each quantity so every unit of the second system appears with a greedy integer count, rounding the smallest unit.
- Level
Medium6 of 10
- Topics
- Implementation, Simulation, Math, String
- Solved
- No attempts yet
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.
- 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.
- If the first system has units, the next lines give internal conversion rules in the form
a unit1 = b unit2, where and are positive numbers (integer or decimal) and unit1, unit2 are units of the first system. These rules always provide enough information to convert between any two units of the system. - The second system is described immediately afterward in the same format (its unit line followed by its internal rules).
- One conversion rule in the same
a unit1 = b unit2form, where unit1 belongs to the first system and unit2 belongs to the second system. - 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.