Canadian Computing Competition: 1999 Stage 2, Day 2, Problem 2
Mathematicians, as opposed to computer scientists, write expressions using single lower case letters as variables. Addition is represented by a plus sign and multiplication is represented by placing the variables or expressions adjacent with no symbol in between. Multiplication is done before addition unless the addition is parenthesized.
For this problem, we consider mathematical expressions consisting of only variables, addition, multiplication, and parentheses. (There are no other symbols, like spaces, division, subtraction, or numerals in the input or output.) For example,
a+b+c
xyz
xyz+ab+cd
(a+b)(c+d)e
Your task is to read in a number of expressions in this notation and to rearrange each, using the laws of algebra, into equivalent expressions with no parentheses. For example,
(a+b)(c+d)e
can be re-expressed as
ace+ade+bce+bde
If there are several solutions, any one will do. The order of variables within terms does not matter, nor does the order of terms within the expression. You do not need to collect like terms; indeed, this is impossible as there are to be no numerals in the output.
Input Specification
The first line of input contains an integer . lines of input follow, each containing a valid expression as described above. No input line exceeds characters.
Output Specification
Your output should consist of lines, each giving a parenthesis-free expression equivalent to the corresponding line of input.
Sample Input
5
a+b+c
(a+b)(c+d)e
c+cb+a+c
((a+b)+(c+d))e
(a+a)(a+a)
Sample Output
a+b+c
ace+ade+bce+bde
c+cb+a+c
ae+be+ce+de
aa+aa+aa+aa
Comments