题目:
This time, you are supposed to find A+B where A and B are two polynomials.
Input Specification:
Each input file contains one test case. Each case occupies 2 lines, and each line contains the information of a polynomial:
K N_1 a_N_1 N_2 a_N_2 ... N_K a_N_K
where K 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≤N_K<⋯<N_2<N_1≤1000.
Output Specification:
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,输出的多项式系数应当保留1位小数。
(输入的数据中,存在系数没有保留1位小数的情况;计算机浮点数运算可能导致精度丢失问题)
2,多项式系数相加前不为0,相加后可能为0,也不应当输出。
eg.
2 1 1.5 0 2.1
2 2 3.2 1 -1.5
3,不要有多余的空格和换行符。
(特别注意,当相加后所有项系数均为0,不要输出多余空格)
eg.
1 0 -1.5
1 0 1.5
AC代码:
#include <iostream>
#include <algorithm>
#include <iomanip>
#define MAX_K 10
using namespace std;
int K_A;
int K_B;
int exp_A[MAX_K];
int exp_B[MAX_K];
int exp_sum[MAX_K];
double coef_A[MAX_K];
double coef_B[MAX_K];
double coef_sum[MAX_K];
int main() {
cin >> K_A;
for (int i = 0; i < K_A; i++) {
cin >> exp_A[i] >> coef_A[i];
}
cin >> K_B;
for (int i = 0; i < K_B; i++) {
cin >> exp_B[i] >> coef_B[i];
}
int max_exp_A = *max_element(exp_A, exp_A + K_A);
int max_exp_B = *max_element(exp_B, exp_B + K_B);
int exp;
if (max_exp_A >= max_exp_B) {
exp = max_exp_A;
} else {
exp = max_exp_B;
}
int count = 0;
while (exp >= 0) {
double coef1 = 0, coef2 = 0;
auto iter_A = find(exp_A, exp_A + K_A, exp);
if (iter_A != exp_A + K_A) {
coef1 = coef_A[iter_A - exp_A];
}
auto iter_B = find(exp_B, exp_B + K_B, exp);
if (iter_B != exp_B + K_B) {
coef2 = coef_B[iter_B - exp_B];
}
if ( (coef1 != 0 || coef2 != 0) && coef1 + coef2 != 0) {
coef_sum[count] = coef1 + coef2;
exp_sum[count] = exp;
count++;
}
exp--;
}
cout << fixed;
if(count != 0)
cout << count << " ";
else
cout << count;
for (int i = 0; i < count; i++) {
if(i != count -1)
cout << exp_sum[i] << " " << setprecision(1) << coef_sum[i] << " ";
else
cout << exp_sum[i] << " " << setprecision(1) << coef_sum[i];
}
return 0;
}