P2382 Molecular Formula
Background
Yuanshou (Yuánshǒu) and Yuanlao (Yuánlǎo) are working hard to learn chemistry, and they want the computer to help them simulate molecular formulas to reduce their workload. Please help them by designing a program.
Description
Your task is to write a program that can process molecular formulas in a virtual chemistry setting. In real chemistry, each molecular formula describes a molecule consisting of one or more atoms, but it may not correspond to a real chemical substance.
Below are the definitions of atomic symbols and molecular formulas:
- An atom in a molecule is represented by an atomic symbol. An atomic symbol consists of a single uppercase letter, or an uppercase letter followed by a lowercase letter. For example: H and He are both atomic symbols.
- A molecular formula is a non-empty sequence of atomic symbols. For example, HHHeHHHe is a molecular formula that represents a molecule containing 4 H and 2 He.
- For convenience, a consecutive repetition of the same expression, such as x...x (that is, $n$ copies of $X$, where $2 \le n \le 99$), can be abbreviated as (X)$n$. If $X$ is a single atomic symbol, the parentheses can be omitted. For example, HHHeHHHe can also be written as H2HeH2He, (HHHe)2, (H2He)2, or ((H)2He)2.
The definition of a molecular formula can be described using a formal grammar. In short, the syntax is as follows:
Molecule: Atom | Atom Number | (Molecule) Number | Molecule Molecule
Atom: Uppercase | Uppercase Lowercase
Number: 2 | 3 | 4 | 5 | … | 99
Uppercase: A | B | … | Z
Lowercase: a | b | c | … | z
In this virtual chemistry world, every atom has its atomic mass. Given the atomic masses, your program must output the molecular mass of a molecule represented by its formula. The mass of a molecule is defined as the sum of the masses of all atoms it contains. For example, if the atomic masses of H and He are 1 and 4, then the molecular mass of (H2He)2 is 12.
Input Format
The input consists of two parts.
The first part is an atom table, consisting of several lines. Each line contains an atomic symbol, one or more spaces, and the atomic mass of that atom ($\le 1000$). No two lines contain the same atomic symbol.
The last line of the first part contains only the string "END_OF_FIRST_PART".
The second part is a sequence of lines. Each line is a molecular formula, with no more than 80 characters and no spaces. A molecule contains at most $10^5$ atoms. Some molecules may contain atoms that do not appear in the atom table.
The last line contains a single zero, indicating the end of input.
Output Format
Output a sequence of lines, with the same number of lines as the second part of the input. If every atom in the molecule appears in the atom table, output an integer representing the molecular mass. Otherwise, output UNKNOWN. Do not output extra characters.
Explanation/Hint
Translated by ChatGPT 5