#P2382. Molecular Weight Calculator in Virtual Chemistry
Molecular Weight Calculator in Virtual Chemistry
Molecular Weight Calculator in Virtual Chemistry
Your task is to write a program that calculates the molecular weight of a molecule given in a virtual chemistry system. In genuine chemistry, a molecule is described by one or more atoms, but in this virtual setting, the molecule might not represent a real chemical substance.
A molecule is represented by a molecular formula following the rules below:
- An atom is represented by an atomic symbol, which is either a single uppercase letter or an uppercase letter followed by a lowercase letter (e.g. H or He).
- A molecule is a non-empty sequence of atoms, for example, HHHeHHHe represents a molecule containing 4 H atoms and 2 He atoms.
- For convenience, a consecutive sequence of the same formula, say X...X (with n copies of X, where \(2 \le n \le 99\)), can be abbreviated as \((X)_{n}\). If X is just an atomic symbol, the parentheses can be omitted. For instance, the molecule HHHeHHHe can also be written as H2HeH2He, \((HHHe)_2\), or \(((H)_2He)_2\).
The grammar for a molecular formula can be described as follows (all numbers in the formulas must be rendered in \( \LaTeX \) format):
Molecule : Atom | Atom Number | ( Molecule ) Number | Molecule Molecule Atom : Uppercase | Uppercase Lowercase Number : 2 | 3 | 4 | \ldots | 99 Uppercase : A | B | \ldots | Z Lowercase : a | b | c | \ldots | z
In this virtual chemistry, every atom has its own atomic mass. You are given the atomic masses for some atoms and a molecular formula. Your program must compute and output the molecular weight, defined as the sum of the atomic masses each multiplied by its frequency in the molecule.
For example, if the atomic masses for H and He are 1 and 4 respectively, then the molecular weight of \((H_2He)_2\) is \(2 \times (2\times1 + 4) = 12\).
inputFormat
The input consists of:
- An integer \(N\) (\(1 \le N \le 26\)) on the first line, representing the number of atomic types provided.
- The next \(N\) lines each contain an atomic symbol and its atomic mass (an integer), separated by a space.
- A line containing the molecular formula.
You can assume that each atomic symbol appears at most once in the list, and the molecular formula follows the grammar described above.
outputFormat
Output the molecular weight as an integer.
sample
2
H 1
He 4
(H2He)2
12