# 数据结构与算法——多项式加法

﻿﻿

我们经常遇到两多项式相加的情况，在这里，我们就需要用程序来模拟实现把两个多项式相加到一起。首先，我们会有两个多项式，每个多项式是独立的一行，每个多项式由系数、幂数这样的多个整数对来表示。

#include <vector>
#include "iostream"
using namespace std;

struct Pair{
int a;
int b;
};

int main()
{
int n;
cin >> n;
for (int i = 0;i < n;i++) {
vector<Pair> ps;
int tempa, tempb, count = 0;
while (count < 2) {
cin >> tempa >> tempb;
if (tempb >= 0) {
Pair p;
p.a = tempa;
p.b = tempb;
ps.push_back(p);
}
else {
count++;
//cin.ignore(300, '\n');
}
}
int len = ps.size();
for (int j = 0;j < len - 1;j++) {
for (int k = j + 1;k < len;k++) {
if (ps[j].b < ps[k].b) {
Pair temp = ps[k];
ps[k] = ps[j];
ps[j] = temp;
}
}
}
for (int j = 0;j < len - 1;j++) {
if (ps[j].b == ps[j + 1].b) {
ps[j].a += ps[j + 1].a;
ps.erase(ps.begin() + j + 1);
len--;
j--;
}
}

len = ps.size();
for (int j = 0;j < len;j++) {
if (ps[j].a == 0) {
ps.erase(ps.begin() + j);
len--;
j--;
}
}

for (int j = 0;j < ps.size();j++) {
cout << "[ " << ps[j].a << ' ' << ps[j].b << " ] ";
}
cout << endl;
}
return 0;
}

#include <iostream>
#include <vector>
#include <map>
using namespace std;

int main() {
int n;
cin >> n;
for (int i = 0; i != n; ++i) {
map <int, int> ploy;
int index, value, over = 0;
while (cin >> value >> index) {
if (index < 0)
over++;
else {
pair <map <int, int>::iterator, bool> ret =
ploy.insert(make_pair(index, value));
if (!ret.second)
ret.first->second += value;
}
if (over == 2)
break;
}
for (map <int, int>::reverse_iterator riter = ploy.rbegin();
riter != ploy.rend(); ++riter) {
if (riter->second != 0)
cout << "[ " << riter->second << ' ' << riter->first << " ] ";
}
cout << endl;
}
return 0;
}