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 a~N1~ N2 a~N2~ ... NK a~NK~, where K is the number of nonzero terms in the polynomial, Ni and a~Ni~ (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

注意点:当指数相同的项相加的时候,如果系数为0,则不压入ans中。
这一题同链表来实现更加简便

 1 #include<iostream>
 2 #include<vector>
 3 using namespace std;
 4 struct node{
 5   int exp; 
 6   double coe;
 7 };
 8 int main(){
 9   int n, m, i, j;
10   vector<node> v1, v2, ans;
11   node temp;
12   cin>>n;
13   for(i=0; i<n; i++){
14     cin>>temp.exp>>temp.coe;
15     v1.push_back(temp);
16   }
17   cin>>m;
18   for(i=0; i<m; i++){
19     cin>>temp.exp>>temp.coe;
20     v2.push_back(temp);
21   }
22   for(i=0, j=0; i<v1.size()&&j<v2.size();){
23     if(v1[i].exp>v2[j].exp){ ans.push_back(v1[i]); i++;}
24     else if(v1[i].exp<v2[j].exp){ans.push_back(v2[j]); j++;}
25     else{v1[i].coe+=v2[j].coe; if(v1[i].coe!=0.0){ans.push_back(v1[i]);} i++; j++;}
26   }
27   if(i<v1.size())
28     for(; i<v1.size(); i++) ans.push_back(v1[i]);
29   if(j<v2.size())
30     for(; j<v2.size(); j++) ans.push_back(v2[j]);
31   cout<<ans.size();
32   for(i=0; i<ans.size(); i++) printf(" %d %.1f", ans[i].exp, ans[i].coe);
33   return 0;
34 }

猜你喜欢

转载自www.cnblogs.com/mr-stn/p/9152506.html