1002 A+B for Polynomials (25)(25 分)
This time, you are supposed to find A+B where A and B are two polynomials.
Input
Each input file contains one test case. Each case occupies 2 lines, and each line contains the information of a polynomial: K N1 a~N1~ N2 a~N2~ ... NK a~NK~, where K is the number of nonzero terms in the polynomial, Ni and a~Ni~ (i=1, 2, ..., K) are the exponents and coefficients, respectively. It is given that 1 <= K <= 10,0 <= NK < ... < N2 < N1 <=1000.
Output
For 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.5
Sample Output
3 2 1.5 1 2.9 0 3.2
题解1:
该题首先需要注意数据类型。
使用数组标签的方式记录数据,result[exponent]=coefficient。
考虑到最后需要先输出多项式的项数,每次读取result的时候记录项数。这里使用总数a+b减去多余项数的方式,即,如果第二组中有和第一组中相同的项,总数减1,如果两项系数相加和为0,总数再减1。
也可以先把所有项的系数相加,最后统计项数。
最后输出项数和所有系数不为0的项。输出保留1位小数,使用setprecision(n)<<std::fixed。
源代码1:
#include <iostream> #include <iomanip> using namespace std; int main() { int a, b; int expo; double coef; int j; double result[1001] = { 0 }; int count = 0; cin >> a; for (j = 0; j < a; j++) { cin >> expo; cin >> result[expo]; } cin >> b; for (j = 0; j < b; j++) { cin >> expo >> coef; if ((result[expo]) != 0) { count++; result[expo] += coef; if (result[expo] == 0) count++; } else result[expo] = coef; } cout << a + b - count; for (j = 1000; j >=0; j--) { if (result[j] != 0) cout << " " << j << " " << setprecision(1)<< std::fixed << result[j]; } return 0; }