#P1067. Formatting a Polynomial
Formatting a Polynomial
Formatting a Polynomial
Given a univariate polynomial expressed as
$$f(x)=a_nx^n+a_{n-1}x^{n-1}+\cdots+a_1x+a_0,\quad a_n\ne0, $$each term is represented by its exponent and coefficient. Your task is to output the polynomial as a string following these rules:
- The variable is
x
and the terms must be arranged in descending order of exponent. - Omit any term whose coefficient is 0.
- If the highest degree term has a positive coefficient, do not print a leading '+'; if it is negative, start with a '-' sign.
- For non-leading terms, prefix with '+' (if the coefficient is positive) or '-' (if negative). Follow the sign immediately with the absolute value of the coefficient (as a positive integer) except when the term's absolute coefficient is 1 and the exponent is greater than 0 (in which case omit the number).
-
The format for the variable part:
- If the exponent \(b > 1\), output it as
x^b
(i.e.x^b
in latex: \(x^b\)). - If the exponent is exactly 1, output it as
x
. - If the exponent is 0, output only the coefficient.
- If the exponent \(b > 1\), output it as
- No extra spaces should appear at the beginning or end of the output string.
Note: The input always contains at least one non-zero coefficient and the highest degree term has a non-zero coefficient.
inputFormat
The first line contains an integer n
representing the number of terms. The following n
lines each contain two integers: the exponent and the coefficient of a term, separated by a space.
outputFormat
Output the formatted polynomial string as described.
sample
3
2 1
1 2
0 3
x^2+2x+3