1002. A+B for Polynomials (25)
2014-11-08 13:23
357 查看
This time, you are supposed to find A+B where A and B are two polynomials.InputEach input file contains one test case. Each case occupies 2 lines, and each line contains the information of a polynomial: K N1 aN1 N2 aN2 ... NK aNK, whereK is the number of nonzero terms in the polynomial, Ni and aNi (i=1, 2, ..., K) are the exponents and coefficients, respectively. It is given that 1 <= K <= 10,0 <= NK < ... < N2 < N1 <=1000.OutputFor each test case you should output the sum of A and B in one line, with the same format as the input. Notice that there must be NO extra space at the end of each line. Please be accurate to 1 decimal place.Sample Input
2 1 2.4 0 3.2 2 2 1.5 1 0.5Sample Output
3 2 1.5 1 2.9 0 3.2
指数相同时系数相加,结果不为1时放入结果,指数不相同时依次放入结果中
#include <iostream> #include <cstdio> using namespace std; /* A和B是两个多项式, exponents为指数,coefficients为系数 * * */ struct Poly { int ex; float co; }; Poly A[10]; Poly B[10]; Poly C[20]; int main(void) { int m, n; scanf("%d", &m); for (int i = 0; i < m; ++i) scanf("%d%f", &A[i].ex, &A[i].co); scanf("%d", &n); for (int i = 0; i < n; ++i) scanf("%d%f", &B[i].ex, &B[i].co); int i = 0, j = 0, k = 0; while (i < m && j < n) { if (A[i].ex > B[j].ex) { C[k].ex = A[i].ex; C[k].co = A[i].co; ++i; ++k; } else if(A[i].ex == B[j].ex) { if (A[i].co + B[j].co != 0) //注意这里一定要先判断A[i].co + B[j]是否等于0,如果等于0不用放入结果中,如果不等于0,则放入结果中 { C[k].ex = A[i].ex; C[k].co = A[i].co + B[j].co; ++k; } ++i; ++j; } else { C[k].ex = B[j].ex; C[k].co = B[j].co; ++j; ++k; } } while (i < m) { C[k].ex = A[i].ex; C[k].co = A[i].co; ++i; ++k; } while (j < n) { C[k].ex = B[j].ex; C[k].co = B[j].co; ++j; ++k; } printf("%d", k); for (i = 0; i < k; ++i) printf(" %d %.1f", C[i].ex, C[i].co);//把空格的输出放到这里 printf("\n"); return 0; }[/code]
相关文章推荐
- PAT 1002. A+B for Polynomials (25)
- 1002. A+B for Polynomials (25)
- [PAT]1002. A+B for Polynomials(25)
- PAT 1002. A+B for Polynomials (25)
- PAT甲级真题及训练集(3)--1002. A+B for Polynomials (25)
- PAT 1002. A+B for Polynomials (25)
- 浙大PAT (Advanced Level) Practise 1002. A+B for Polynomials (25)
- 1002. A+B for Polynomials (25)
- PAT 甲级 1002. A+B for Polynomials (25)
- PAT甲级1002. A+B for Polynomials (25)
- PAT甲级 1002. A+B for Polynomials (25)
- 1002. A+B for Polynomials (25)
- 1002. A+B for Polynomials (25)
- 1002. A+B for Polynomials (25)
- 1002. A+B for Polynomials (25)[C语言]
- 【PAT】1002. A+B for Polynomials (25)
- PAT甲级-1002. A+B for Polynomials (25)
- PAT 1002. A+B for Polynomials (25)
- 1002. A+B for Polynomials (25)
- 1002. A+B for Polynomials (25)