Balanced Reactions

View as PDF

Submit solution

Points: 7
Time limit: 2.0s
Memory limit: 64M

Author:
Problem type

In Chemistry all elements are represented as one or two characters. The element always begins with a capital letter and if there is a second letter it is always a lowercase. Sometimes multiple elements can be combined to create a single compound. When multiple of a given element is included in this compound a number representing the quantity of that element is appended to the end of the element's letter code. It is also possible for an element to appear more than once in a compound, for example HHO is the same as H2O and HOH.
Some compounds and elements can be further added together to form chemical reactions that result in a different set of compounds and elements. However, the resultant products must in total add up to the exact same quantity of the exact same elements as the initial reactants. These chemical reactions can be denoted as a mathematical equation where compounds on the left side are added together to equal the compounds on the right side. For example:
H3O+F2=H2F2+HO
This is a valid reaction as the total number of each element on the right side equals those on the left side. Such a reaction is called 'balanced'.
HO+Ca=Ca2O+H
This reaction is not balanced as the left side has a single Ca element however the right side has two. Such a reaction is called 'unbalanced'.
Given a chemical reaction, determine if it is balanced.

Input Specification

The only line of input is the chemical reaction in the form A+B+C...+F=G+H...+J.

Output Specification

Print balanced or unbalanced depending on the reaction.

Sample Input

CaCO3+H2SO4=CaSO4+H2O+CO2

Sample Output

balanced

Explanation for Sample

On the left side of the reaction we have CaCO3+H2SO4. The quantity of each element is as follows:

Ca 1
C 1
O 7
H 2
S 1

On the right side of the reaction we have CaSO4+H2O+CO2. The quantity of each element is exactly the same as the left side so the reaction is balanced.


Comments


  • 0
    Eric_Zhang  commented on Oct. 25, 2020, 5:04 p.m. edited

    Worst case doesn't have that many characters :) But the int values can get really big 0.0


  • 0
    jsumabat  commented on March 7, 2020, 4:16 p.m.

    Is it guaranteed that the integer will always be a single-digit?