This time, you are supposed to find A+B where A and B are two polynomials.
Input Specification:
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, Niand aNi(i=1,2,⋯,K) are the exponents and coefficients, respectively. It is given that 1≤K≤10,0≤NK<⋯<N2<N1≤1000.
Output Specification:
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<stdlib.h>
using namespace std;
typedef struct Nomial
{
int index;
double ceof;
}Nomial,*Polynomials;
int isNomialsEqual(int in1 , int in2);//compare nomial's index in A and B.
void inputPolynomials(Polynomials &N , int k);//input polynomials
int main()
{
//input
int k1,k2;
Polynomials A,B;
cin>>k1;
inputPolynomials(A , k1);
cin>>k2;
inputPolynomials(B , k2);
//works
int i = 0 , j=0 , k3 = 0;
Polynomials C;
C = (Polynomials)malloc((k1+k2)*sizeof(Nomial));
if(!C)return -2;
while( i<k1 && j<k2)
{
switch(isNomialsEqual(A[i].index , B[j].index))
{
case 1:
C[k3].index = A[i].index;
C[k3].ceof = A[i].ceof;
i++;
k3++;
break;
case 0:
C[k3].index = A[i].index;
C[k3].ceof = A[i].ceof + B[j].ceof;
i++;j++;
k3++;
break;
default:
C[k3].index = B[j].index;
C[k3].ceof = B[j].ceof;
j++;
k3++;
break;
}
}
while(i<k1)
{
C[k3].index = A[i].index;
C[k3].ceof = A[i].ceof;
k3++;
i++;
}
while(j<k2)
{
C[k3].index = B[j].index;
C[k3].ceof = B[j].ceof;
k3++;
j++;
}
//output
// cout<<k3;
int account = 0;
for(i=0;i<k3;i++)
{
if(C[i].ceof!=0)account++;
}
cout<<account;
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(1);
for(i=0;i<k3;i++)
{
if(C[i].ceof !=0 )
{
cout<<" "<<C[i].index<<" "<<C[i].ceof;
}
}
return 0;
}
void inputPolynomials(Polynomials &N, int k)
{
N = (Polynomials)malloc(k*sizeof(Nomial));
for(int i=0;i<k;i++)
{
cin>>N[i].index>>N[i].ceof;
}
}
int isNomialsEqual(int in1, int in2)
{
if(in1>in2)
{
return 1;
}
else if(in1 == in2)
{
return 0;
}
else
{
return -1;
}
}