24h購物| | PChome| 登入
2012-05-24 07:06:03| 人氣1,024| 回應0 | 上一篇 | 下一篇

[UVA][字串處理] 392 - Polynomial Showdown

推薦 0 收藏 0 轉貼0 訂閱站台


 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 and Output

The input file 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. The output file 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


#include <stdio.h>
#include <stdlib.h>

int main() {
int p[9], i, j;
while(scanf("%d", &p[8]) == 1) {
for(i = 7; i >= 0; i--)
scanf("%d", &p[i]);
j = 8;
while(!p[j] && j >= 0) j--;
int flag = 0;
if(j == -1)
putchar('0');
for(i = j; i >= 0; i--) {
if(p[i]) {
if(flag) {
putchar(' ');
if(p[i] > 0)
putchar('+');
else
putchar('-');
putchar(' ');
} else {
if(p[i] < 0)
putchar('-');
flag = 1;
}
if(i) {
if(abs(p[i]) != 1)
printf("%d", abs(p[i]));
putchar('x');
if(i != 1)
printf("^%d", i);
}
else {
printf("%d", abs(p[i]));
}
}
}
puts("");
}
return 0;
}


台長: Morris
人氣(1,024) | 回應(0)| 推薦 (0)| 收藏 (0)| 轉寄
全站分類: 不分類 | 個人分類: UVA |
此分類下一篇:[UVA][幾何] 438 - The Circumference of the Circle
此分類上一篇:[UVA][zkw式ST] 10015 - Joseph's Cousin

是 (若未登入"個人新聞台帳號"則看不到回覆唷!)
* 請輸入識別碼:
請輸入圖片中算式的結果(可能為0) 
(有*為必填)
TOP
詳全文