문제
Chemistry is all about reactions—you throw a bunch of stuff into a test-tube, heat it up, hoping that it will neither explode or poison you, then cool it down and try to work out whether what you have is what you expected. That’s the easy (and fun) bit—much harder is recording it all. As is usual with skills of this type, chemistry instructors the world over rely on drill—a seemingly endless set of reactions that the students have to complete. The trick is that everything that appears on the left side (the reagents, or ‘input’) must appear on the right side (the products, or ‘output’). This ought to be simple, but generations of chemistry students have demonstrated otherwise.
Professor Plumbius is getting tired of writing the same comments on his student’s worksheets over and over and he wants to automate the process. He wants to be able to enter the equations as written by the students and have the computer produce the comments automatically, thus giving him more time to dream up more equations to give his students to practise on. This is where you come in.
Write a program that will read in a chemistry equation and determine whether it is balanced. If it isn’t, your program must tell the student what elements are out of balance and by how much.
Normally a chemistry equation is written like this:
2H2O + SO2 ←→ H2 + H2SO4
but due to the limitations of computer input we will present it like this:
2H2O + SO2 = H2 + H2SO4
This example shows the essentials of an equation: each side consists of one or more molecules, separated by ‘+’ signs (the spaces are optional). Each molecule may have a multiplier before it which specifies how many instances of that molecule take part in the reaction. A molecule consists of one or more elements. Each element has a symbol, which is either an uppercase letter, e.g., ‘H’, or an uppercase letter followed by a lowercase letter, e.g., ‘Br’. A symbol may be followed by a multiplier specifying how many atoms of that element are present in that part of the molecule. Thus the first term says that there are two instances of a molecule consisting of two atoms of H and one atom of O. (This happens to be water, but you do not need to know that.)
Given that these are exercises handed out to the students, the left hand sides are, by definition, correct. Thus your job is to determine whether all the atoms that appear on the left also appear on the right. If they do, then the equation is balanced. If not, you must report which elements have been created or lost and how much of each.