PAT A 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

 

求多项式和,无难度。

和的系数如果在 (-0.05,0.05) 则相应项应舍弃。

 

代码:

#include <iostream>
using namespace std;

int main()
{
	int n1,n2,n,i,j;
	int e1[11],e2[11],e[20];	//n1指数,n2指数,和指数
	double c1[10],c2[10],c[20];	//n1系数,n2系数,和系数

	cin>>n1;	//输入
	for(i=0;i<n1;i++)
	{
		cin>>e1[i];
		cin>>c1[i];
	}
	e1[i]=-1;
	cin>>n2;
	for(i=0;i<n2;i++)
	{
		cin>>e2[i];
		cin>>c2[i];
	}
	e2[i]=-1;
	n=0;
	i=0;
	j=0;

	while(i<n1||j<n2)	//求和
	{
		if(e1[i]>e2[j])	//确切说,前两个判断也需要增加数的范围,因为没有限定输入符合0.1的要求
		{
			e[n]=e1[i];
			c[n++]=c1[i++];
		}
		else if(e1[i]<e2[j])
		{
			e[n]=e2[j];
			c[n++]=c2[j++];
		}
		else if(c1[i]+c2[j]>=0.05||c1[i]+c2[j]<=-0.05)	//注意一位精度,导致和可能不到0.1,则不显示
		{
			e[n]=e1[i];
			c[n++]=c1[i++]+c2[j++];
		}
		else	//注意一位精度,导致和可能不到0.1,则不显示
		{
			i++;
			j++;
		}
	}

	cout<<fixed;	//输出
	cout.precision(1);
	cout<<n;
	for(i=0;i<n;i++)
		cout<<" "<<e[i]<<" "<<c[i];

	return 0;
}


 

你可能感兴趣的:(C++,pat)