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 N1 aN1 N2 aN2 ... NK aNK
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≤NK<⋯<N2<N1≤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
个人思路
这题就是求多项式的和,两种思路,一种是用两个数组存,然后最后逐个比较最后输出,还有一种就是用一个大小为1000的double数组存储指数为i,系数为poly[i]的项,在输入的时候就合并到其中。最后从大到小输出即可。我实现的是第二种思路。
有一个小坑,就是题目要求精确到1位小数,已在题目中加粗。
代码实现
#include <cstdio>
#include <cstring>
#include <string>
#include <set>
#include <map>
#include <vector>
#include <cmath>
#include <algorithm>
#include <iostream>
#define ll long long
#define ep 1e-5
#define INF 0x7FFFFFFF
const int maxn = 1005;
using namespace std;
int main() {
double poly[maxn];
memset(poly, 0, sizeof(poly));
int k1, k2, k = 0;
// 输入第一个多项式
cin >> k1;
for (int i = 0; i < k1; i ++) {
int idx;
cin >> idx;
cin >> poly[idx];
}
// 在输入第二个多项式的同时合并
cin >> k2;
for (int i = 0; i < k2; i ++) {
int idx;
double tmp;
cin >> idx >> tmp;
poly[idx] += tmp;
}
// 统计多项式和的项数
int max = 0;
for (int i = 0; i < maxn; i ++) {
if (poly[i] != 0) {
k ++;
max = i;
}
}
// 输出
cout << k;
for (int i = max; i >= 0; i --) {
if (poly[i] != 0) {
printf(" %d %.1lf",i, poly[i]); }
}
return 0;
}
总结
学习不息,继续加油