​1002 A+B for Polynomials (25分)​

题目

给出两个多项式的系数和指数,求相加后的多项式系数和指数。

分析

用 map 存系数和指数的对应关系,将系数加到相同的指数里面即可。
注意只需要输出不为零的项。

#include <bits/stdc++.h>
using namespace std;
#define db(x) cout<<x<<endl

typedef long long ll;
const int INF = 0x3f3f3f3f;
const int N = 1e4 + 10;
const ll mod = 2147483648;

int n, m;
map<int, double, greater<int> > mp;
double ans[N];
int a; double b;

int main() {
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d%lf", &a, &b);
mp[a] += b;
}
scanf("%d", &m);
for (int i = 0; i < m; i++) {
scanf("%d%lf", &a, &b);
mp[a] += b;
}
int cnt = 1;
for (map<int, double>::iterator it = mp.begin(); it != mp.end(); it++) {
if (it->second == 0) continue;
ans[cnt++] = it->first;
ans[cnt++] = it->second;
}
if (cnt == 1) {
printf("0\n"); return 0;
}
printf("%d ", cnt >> 1);
for (int i = 1; i < cnt; i += 2) {
printf("%.0lf %.1lf%c", ans[i], ans[i + 1], " \n"[i==cnt-2]);
}
return 0;
}