题目链接1002 A+B for Polynomials
题意:求两个多项式相加,类似于链表的合并,用结构体将幂值,和系数存起来。幂值不同,大的存到答案结构体数组中,指针向后移一位,相同将系数相加,并且判断是否为0为0则不存。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
const int maxn = 1010;
typedef struct polynomial{
int ex;
double co;
}Node;
int main(int argc, char** argv) {
int k1, k2;
Node node1[maxn], node2[maxn], ans[maxn];
scanf("%d", &k1);
for (int i = 0; i < k1; i++)
scanf("%d%lf", &node1[i].ex, &node1[i].co);
scanf("%d", &k2);
for (int i = 0; i < k2; i++)
scanf("%d%lf", &node2[i].ex, &node2[i].co);
int i, j, m;
i = j = m = 0;
while (i < k1 && j < k2) {
if (node1[i].ex > node2[j].ex) {
ans[m].ex = node1[i].ex;
ans[m++].co = node1[i++].co;
} else if (node1[i].ex < node2[j].ex) {
ans[m].ex = node2[j].ex;
ans[m++].co = node2[j++].co;
} else {
double t = node1[i++].co + node2[j++].co; // 坑点,系数相加可能为0
if (t != 0) {
ans[m].ex = node1[i - 1].ex;
ans[m++].co = t;
}
}
}
Node *p;
p = node1;
if (j < k2) {
i = j;
k1 = k2;
p = node2;
}
for (; i < k1; i++) {
ans[m].ex = p[i].ex;
ans[m++].co = p[i].co;
}
printf("%d", m);
for (i = 0; i < m; i++) {
printf(" %d %.1f", ans[i].ex, ans[i].co);
}
return 0;
}