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
1 #include <iostream> 2 #include <cstdio> 3 #include <vector> 4 5 using namespace std; 6 class node{ 7 public: 8 int expon;//exponents 9 double coe;//coefficients 10 node(int _expon, double _coe) :expon(_expon), coe(_coe){} 11 ~node(){} 12 }; 13 14 15 int main(void) 16 { 17 int N1; 18 cin >> N1; 19 vector<node> List1; 20 for (size_t i = 0; i < N1; i++) 21 { 22 int expon; double coe; 23 cin >> expon >> coe; 24 List1.push_back(node(expon, coe)); 25 } 26 int N2; 27 cin >> N2; 28 vector<node> List2; 29 for (size_t i = 0; i < N2; i++) 30 { 31 int expon; double coe; 32 cin >> expon >> coe; 33 List2.push_back(node(expon, coe)); 34 } 35 36 vector<node>::iterator it1, it2; 37 it1 = List1.begin(); it2 = List2.begin(); 38 39 vector<node> List3; 40 while( (it1 != List1.end()) && (it2 !=List2.end()) ) 41 { 42 43 if ((*it1).expon == (*it2).expon) 44 { 45 46 double coe_sum = (*it1).coe + (*it2).coe; 47 if (coe_sum != 0) 48 List3.push_back(node((*it1).expon, coe_sum)); 49 it1++; it2++; 50 } 51 else if ((*it1).expon > (*it2).expon) 52 { 53 List3.push_back(node((*it1).expon, (*it1).coe)); 54 it1++; 55 } 56 else if ((*it1).expon < (*it2).expon) 57 { 58 List3.push_back(node((*it2).expon, (*it2).coe)); 59 it2++; 60 61 } 62 63 } 64 while (it1 != List1.end()){ List3.push_back(node((*it1).expon, (*it1).coe)); it1++; } 65 while (it2 != List2.end()){ List3.push_back(node((*it2).expon, (*it2).coe)); it2++; } 66 67 cout << List3.size(); 68 for (size_t i = 0; i < List3.size(); i++) 69 { 70 cout << " " << List3[i].expon; 71 printf(" %0.1f", List3[i].coe); 72 } 73 cout << endl; 74 return 0; 75 }
分析: 只需要注意一下输出的格式即好,这里用了C里面的输出函数