因为多项式最高次只有1000,用数组保存多项式比较简单,数组下标对应多项式次数,保存的数字对应多项式系数。
相加后,将系数不为0的项输出即可。
#include<cstdio>
int main() {
double p1[1001] = { 0 }, p2[1001] = { 0 }, res[1001] = { 0 };
int n1, n2;
scanf("%d", &n1);
for (int i = 0;i < n1;i++) {
int exp;
double val;
scanf("%d %lf", &exp, &val);
p1[exp] = val;
}
scanf("%d", &n2);
for (int i = 0;i < n2;i++) {
int exp;
double val;
scanf("%d %lf", &exp, &val);
p2[exp] = val;
}
int total = 0;
for (int i = 0;i <= 1000;i++) {
res[i] = p1[i] + p2[i];
if (res[i] != 0)
total++;
}
printf("%d", total);
for (int i = 1000;i >= 0; i--) {
if (res[i] != 0) {
printf(" %d %.1lf", i, res[i]);
}
}
}