#P2281. Polynomial Addition and Multiplication

    ID: 15556 Type: Default 1000ms 256MiB

Polynomial Addition and Multiplication

Polynomial Addition and Multiplication

In today’s math lesson, the teacher discussed addition and multiplication of polynomials. Later, many computation problems were assigned. To save time, Xiao Ming wants to write a program that computes the sum and product of two polynomials.

A polynomial is given as a sum of terms. Each term is represented in the following format:

For example, consider the term 31 W X^3 Y^3 Z^50. Here, if the coefficient is 1 it is omitted (e.g. X Y^2 Z stands for $XY^2Z$), and for any variable X raised to an exponent, it is denoted as X^3 for $X^3$. Variables are single uppercase letters. A term is a sequence of tokens (coefficient and factors) separated by a single space. Different terms in a polynomial are separated by a " + " (space, plus, space) with no extra spaces.

Given two polynomials formatted like the examples below:

X Y^2 Z + 31 W X^3 Y^3 Z^50 + S^3
V^2 + S^3 + 3 W X^3 Y^3

Compute and output their sum and product. In the output, combine like terms (terms with the same variables and corresponding exponents) and present the result in the same format. In both the sum and product, terms should be sorted in lexicographical order based on the tuple of (variable, exponent) in increasing order.

Note: Any constant or integer coefficient is always an integer. Exponents are also integers.

inputFormat

The input consists of two lines. Each line contains a polynomial in the format described above.

For example:

X Y^2 Z + 31 W X^3 Y^3 Z^50 + S^3
V^2 + S^3 + 3 W X^3 Y^3

outputFormat

The output should consist of two lines:

  1. The first line is the sum of the two polynomials.
  2. The second line is the product of the two polynomials.

Terms in the output must be combined if they have the same variables raised to the same exponents, and printed in the specified format.

sample

X Y^2 Z + 31 W X^3 Y^3 Z^50 + S^3
V^2 + S^3 + 3 W X^3 Y^3
2 S^3 + V^2 + 3 W X^3 Y^3 + 31 W X^3 Y^3 Z^50 + X Y^2 Z

S^6 + S^3 V^2 + 3 S^3 W X^3 Y^3 + 31 S^3 W X^3 Y^3 Z^50 + S^3 X Y^2 Z + 31 V^2 W X^3 Y^3 Z^50 + V^2 X Y^2 Z + 3 W X^4 Y^5 Z + 93 W^2 X^6 Y^6 Z^50

</p>