1002. A+B for Polynomials (25)

来源:互联网 发布:华西村软件 编辑:程序博客网 时间:2024/05/07 08:31

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.22 2 1.5 1 0.5
Sample Output
3 2 1.5 1 2.9 0 3.2
#include<iostream>
#include<list>
using namespace std;
struct node{
int ex;
double coe;
}L1[20],L2[20],L3[20];
int main()
{
//freopen("in.txt","r",stdin);
  int len1,len2;
  int i=0;
  cin>>len1;
  
  for(i=0;i<len1;i++)
  {
 cin>>L1[i].ex;
 cin>>L1[i].coe;
  
  }
  cin>>len2;
 
  int j;
  for(j=0;j<len2;j++)
  {
      cin>>L2[j].ex;
 cin>>L2[j].coe;
  
  }
  int k=0;


  for(i=0,j=0;i<len1&&j<len2;)
  {
 
      if(L1[i].ex>L2[j].ex)
 {
 L3[k].ex=L1[i].ex;
 L3[k].coe=L1[i].coe;
     k++;
 i++;
 
 
 }
 else if(L1[i].ex<L2[j].ex)
 {
     L3[k].ex=L2[j].ex;
 L3[k].coe=L2[j].coe;
     k++;  
 j++;
 
 }
 else
 {
  if((L2[j].coe+L1[i].coe)!=0)
  {
        L3[k].ex=L2[j].ex;
    L3[k].coe=L2[j].coe+L1[i].coe;
    
  
    k++;
  }
  i++;
  j++;


 
 }
 
  
  
  }
 
  while(i<len1)
  {
 
          L3[k].ex=L1[i].ex;
 L3[k].coe=L1[i].coe;
     k++;
 i++;

  
  }
  while(j<len2)
  {
    
     L3[k].ex=L2[j].ex;
 L3[k].coe=L2[j].coe;
     k++;  
 j++;
  }
  
  if(k>0)
  {
 cout<<k<<" ";
    for(i=0;i<k-1;i++)
{
       printf("%d %.1lf ",L3[i].ex,L3[i].coe);
  
}
    printf("%d %.1lf",L3[k-1].ex,L3[k-1].coe);
  }
  else
 cout<<k;
  cout<<endl;


  return 0;
}