1002. A+B for Polynomials (25)
时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue
This time, you are supposed to find A+B where A and B are two polynomials.
Input
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
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
#include<iostream>
#include<stdio.h>
#include<vector>
#include<map>
#include<algorithm>
using namespace std;
int main()
{
int K; pair<int, double> p;
vector<pair<int, double> > v1,v2,v;
cin >> K;
for (int i = 0; i < K; i++)
{
cin >> p.first >> p.second;
v1.push_back(p);
}//把指数和系数当成一对加入到容器中,下同
cin >> K;
for (int i = 0; i < K; i++)
{
cin >> p.first >> p.second;
v2.push_back(p);
}
int i = 0, j = 0;
for (int k = 0; k < v1.size()+v2.size(); k++)
{
if (i < v1.size() && j < v2.size())
{
if (v1[i].first == v2[j].first)
{
p.first = v1[i].first;
p.second = v1[i].second + v2[j].second;
if(p.second!=0)
v.push_back(p);
i++; j++;
}
else if (v1[i].first > v2[j].first)
{
v.push_back(v1[i]);
i++;
}
else
{
v.push_back(v2[j]);
j++;
}
}
else if (i < v1.size() && j >= v2.size())
{
v.push_back(v1[i]);
i++;
}
else if (j < v2.size() && i >= v1.size())
{
v.push_back(v2[j]);
j++;
}
else
break;
}//这个for循环利用二路归并排序的做法
if (v.size()>0)
cout << v.size() << " ";
else
cout << "0";//这个地方是坑,假如说两个多项式的和为0,那么只需输出K后面无空格了
for (int k = 0; k < v.size(); k++)
{
//cout << v[k].first << " " << v[k].second;
printf("%d %.1f", v[k].first, v[k].second);//控制格式
if (k != v.size() - 1)
cout << " ";
}
v.clear(); v1.clear(); v2.clear();
}