1002. A+B for Polynomials (25)
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 <cstdio>
#include <vector> using namespace std;
class node{
public:
int expon;//exponents
double coe;//coefficients
node(int _expon, double _coe) :expon(_expon), coe(_coe){}
~node(){}
}; int main(void)
{
int N1;
cin >> N1;
vector<node> List1;
for (size_t i = ; i < N1; i++)
{
int expon; double coe;
cin >> expon >> coe;
List1.push_back(node(expon, coe));
}
int N2;
cin >> N2;
vector<node> List2;
for (size_t i = ; i < N2; i++)
{
int expon; double coe;
cin >> expon >> coe;
List2.push_back(node(expon, coe));
} vector<node>::iterator it1, it2;
it1 = List1.begin(); it2 = List2.begin(); vector<node> List3;
while( (it1 != List1.end()) && (it2 !=List2.end()) )
{ if ((*it1).expon == (*it2).expon)
{ double coe_sum = (*it1).coe + (*it2).coe;
if (coe_sum != )
List3.push_back(node((*it1).expon, coe_sum));
it1++; it2++;
}
else if ((*it1).expon > (*it2).expon)
{
List3.push_back(node((*it1).expon, (*it1).coe));
it1++;
}
else if ((*it1).expon < (*it2).expon)
{
List3.push_back(node((*it2).expon, (*it2).coe));
it2++; } }
while (it1 != List1.end()){ List3.push_back(node((*it1).expon, (*it1).coe)); it1++; }
while (it2 != List2.end()){ List3.push_back(node((*it2).expon, (*it2).coe)); it2++; } cout << List3.size();
for (size_t i = ; i < List3.size(); i++)
{
cout << " " << List3[i].expon;
printf(" %0.1f", List3[i].coe);
}
cout << endl;
return ;
}
分析: 只需要注意一下输出的格式即好,这里用了C里面的输出函数