Molecular Formula
Time limit3sMemory limit128 MB
Parse a nested molecular formula with repetition counts and atomic weight lookups to compute total molecular weight, or report UNKNOWN.
- Level
Medium4 of 10
- Topics
- Recursion, String, Implementation
- Solved
- No attempts yet
Problem
Write a program that computes the weight of a molecule described by a molecular formula in a virtual chemistry. As in real chemistry, each molecular formula represents a molecule made of one or more atoms, though it need not be chemically realistic.
- An atom is written as an atomic symbol: either a single capital letter, or a capital letter followed by a small letter. For example,
HandHeare atomic symbols. - A molecular formula is a non-empty sequence of atomic symbols. For example,
HHHeHHHerepresents a molecule made of fourHatoms and twoHeatoms. - A repetition of the same sub-formula, written times in a row (with an integer from to inclusive), can be abbreviated to
(X)n. The parentheses may be omitted when is a single atomic symbol. For example,HHHeHHHemay also be written asH2HeH2He,(HHHe)2,(H2He)2, or((H)2He)2.
The set of all molecular formulae can be viewed as a formal language. Summarizing the description above, the syntax of molecular formulae is defined as follows.
Molecule → Atom | Atom Number | ( Molecule ) Number | Molecule Molecule
Atom → CapitalLetter | CapitalLetter SmallLetter
Number → 2 | 3 | 4 | · · · | 97 | 98 | 99
CapitalLetter → A | B | C | · · · | X | Y | Z
SmallLetter → a | b | c | · · · | x | y | z
Each atom has its own atomic weight. The molecular weight is the sum of the weights of the constituent atoms. For example, if the atomic weights of H and He are and , then the molecule written (H2He)2 weighs .
Input
The input has two parts.
The first part is the Atomic Table: several lines, each containing an atomic symbol, one or more spaces, and its atomic weight (a positive integer at most ). No two lines share the same atomic symbol. This part ends with a line containing only END_OF_FIRST_PART.
The second part is a sequence of lines, each a molecular formula of at most characters and containing no spaces. A molecule contains at most atoms. Some atomic symbols in a formula may be absent from the Atomic Table. This sequence is terminated by a line containing a single 0.
Output
For each formula in the second part, print one line. If every atomic symbol of the formula appears in the Atomic Table, print its molecular weight as an integer; otherwise print UNKNOWN. Print no extra characters.