Polynomial Showdown
Given the coefficients of a polynomial from degree 8 down to 0, you are to format the polynomial in a readable format with unnecessary characters removed. For instance, given the coefficients 0, 0, 0, 1, 22, -333, 0, 1, and -1, you should generate an output line which displays x^5 + 22x^4 - 333x^3 + x - 1.
The formatting rules which must be adhered to are as follows:
1. Terms must appear in decreasing order of degree.
2. Exponents should appear after a caret `"^".
3. The constant term appears as only the constant.
4. Only terms with nonzero coefficients should appear, unless all terms have zero coefficients in which case the constant term should appear.
5. The only spaces should be a single space on either side of the binary + and - operators.
6. If the leading term is positive then no sign should precede it; a negative leading term should be preceded by a minus sign, as in -7x^2 + 30x + 66.
7. Negated terms should appear as a subtracted unnegated term (with the exception of a negative leading term which should appear as described above). That is, rather than x^2 + -3x, the output should be x^2 - 3x.
8. The constants 1 and -1 should appear only as the constant term. That is, rather than -1x^3 + 1x^2 + 3x^1 - 1, the output should appear as-x^3 + x^2 + 3x - 1.
Input
The input will contain one or more lines of coefficients delimited by one or more spaces. There are nine coefficients per line, each coefficient being an integer with a magnitude of less than 1000.
Output
The output should contain the formatted polynomials, one per line.
Sample Input
0 0 0 1 22 -333 0 1 -1
0 0 0 0 0 0 -55 5 0
Sample Output
x^5 + 22x^4 - 333x^3 + x - 1
-55x^2 + 5x
Source
题目类型:模拟
算法分析:按照多项式加法的过程模拟即可
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
#include <cstdio> #include <iostream> #include <fstream> using namespace std; #define n 9 inline int fabs (int k) { return k < 0 ? -k : k; } int main() { int a[n], i; while (cin >> a[0]) { for (i = 1; i < n; i++) cin >> a[i]; bool first = true; for (i = 0; i < n; i++) if (a[i]) { if (first) { if (a[i] == -1 && i < n - 1) cout << '-'; else if (a[i] != 1 || i == n - 1) cout << a[i]; if (i == n - 2) cout << 'x'; else if (i < n - 1) cout << "x^" << n - i - 1; first = false; } else { cout << ' ' << (a[i] < 0 ? '-' : '+') << ' '; if (fabs (a[i]) != 1 || i == n - 1) cout << fabs (a[i]); if (i == n - 2) cout << 'x'; else if (i < n - 1) cout << "x^" << n - i - 1; } } if (first) cout << 0; cout << endl; } return 0; } |
- « 上一篇:poj1546
- poj1562:下一篇 »