We've Got Chemistry, Babe

Time limit1sMemory limit128 MB

Summary
Parse chemical formulas into atom counts, then find positive integer coefficients with gcd 1 that balance the reaction, or report that none or many exist.
Level

Medium7 of 10

Topics
Math, Number theory, Hash map, Implementation
Solved
No attempts yet

Problem

Barry is a chemistry student who does well except at one thing: balancing chemical equations. A chemical reaction is written as a chemical equation, with the reactants on the left and the products on the right, separated by an arrow. For example, forming aluminum oxide from aluminum and oxygen is written Al + O2 -> Al2O3.

This equation is not balanced: there is one aluminum (Al) atom on the left and two on the right, and there are two oxygen (O) atoms on the left and three on the right. A properly balanced version is 4Al + 3O2 -> 2Al2O3.

When an equation is balanced, all of its coefficients must be positive integers whose greatest common divisor is 11. Harder equations also arise, such as Fe2(SO4)3 + KSCN -> K3Fe(SCN)6 + K2SO4.

The atoms inside a pair of parentheses are all multiplied by the number that immediately follows the closing parenthesis (so this equation has 12 oxygen atoms on the left and six carbon (C) atoms on the right). A chemical symbol appears at most once within any single reactant or product. Given a reaction, determine the coefficients that balance it.

Input

The input contains several test cases. Each test case is a single line that begins with two positive integers rr and pp, the number of reactants and the number of products (each at most 1010). Then come the rr reactants and, after them, the pp products, all separated by spaces. Each reactant or product is a formula built from one or more terms, where a term is a single chemical symbol, a chemical symbol followed by an integer ≥2\ge 2, or a parenthesized formula (one or more terms) followed by an integer ≥2\ge 2. Every chemical symbol is one or two letters, only the first of which is capitalized. No test case uses more than 2020 distinct chemical symbols. A line containing two zeros terminates the input and is not processed.

Output

For each test case, output Case X: (where X is the test case number, starting from 11) followed by the coefficients that balance the equation, in the order the reactants and then the products were given, separated by single spaces. If the equation cannot be balanced at all, or if it can be balanced but not uniquely (more than one set of coefficients works, ignoring common multiples), output the word No instead of the coefficients.

Examples1

  1. Example 1

    Input
    2 1 Al O2 Al2O3
    2 2 Fe2(SO4)3 KSCN K3Fe(SCN)6 K2SO4
    1 1 CO2 CO
    2 2 A B AB B
    0 0
    
    Expected output
    Case 1: 4 3 2
    Case 2: 1 12 2 3
    Case 3: No
    Case 4: No