PTA 1002 A+B for Polynomials (思维)

1002 A+B for Polynomials (25)(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

【分析】

  1. 一开始大概是想复杂了吧,定义了结构体来存储指数和系数,然后排序、合并,然后在合并的时候出了问题,就想着换一个方法吧。。。
  2. 一维数组就可以了,也用不到其他的什么,也不需要排序。系数转换为下标,指数作为该下标对应的元素的值,然后如果i相等的话,正好就相加了。很方便,非常方便。。。输出的时候本来就是按i的一定顺序输出的,所以不用再进行排序了。
  3. 注意,输出的是非0项,如果项数为0,只把0输出就可以了;注意输入的两个数中系数是整型,指数是浮点型,所以输出的时候用printf  占位符来输出。
#include<bits/stdc++.h> 
using namespace std;
double a[1005];
int main()
{
	int t1,t2,cnt=0;
	memset(a,0,sizeof(a));
	int i;
	double t;
	scanf("%d",&t1);
	while(t1--)
	{
		scanf("%d%lf",&i,&t);
		a[i]+=t;
	}
	scanf("%d",&t2);
	while(t2--)
	{
		scanf("%d%lf",&i,&t);
		a[i]+=t;
	}
	for(i=0;i<1005;i++)
	{
		if(a[i]!=0)cnt++;	
	}	
	cout<<cnt;
	
	if(cnt)
	{
		cout<<" ";
		for(i=1001;i>=0;i--)
		{
			if(a[i]!=0)
			{
				cout<<i<<" ";
				printf("%.1lf",a[i]);
				cnt--;
				if(cnt)cout<<" ";
			}
		}
		cout<<endl;
	}
		
	return 0;	
}

猜你喜欢

转载自blog.csdn.net/qq_38735931/article/details/81430118