A+B for Polynomials

Q: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

A:  two pointers问题,注意一个细节就好:当两个系数相加时,可能和为0,此时,非零项计数不能把这项包括在内。

#include <stdio.h>


int main()
{
	int K1,K2,K,exps1[10],exps2[10],exp[20];
	int i,j;
	float coes1[10],coes2[10],coe[20];
	scanf("%d ",&K1);
	for(i=0;i<K1;i++)
	{
		scanf("%d",&exps1[i]);
		scanf("%f",&coes1[i]);
	}
	scanf("%d ",&K2);
	for(i=0;i<K2;i++)
	{
		scanf("%d",&exps2[i]);
		scanf("%f",&coes2[i]);
	}
	i=j=K=0;
	while (i<K1&&j<K2)
	{
		if(exps1[i]==exps2[j])
		{
			exp[K] = exps1[i];
			coe[K] = coes1[i]+coes2[j];
			if(coe[K]!=0)            //注意相加之后,可能这一项的系数为0
				K++;
			i++;
			j++;
		}else if(exps1[i]>exps2[j])
		{
			exp[K] = exps1[i];
			coe[K] = coes1[i];
			K++;
			i++;
		}else
		{
			exp[K] = exps2[j];
			coe[K] = coes2[j];
			K++;
			j++;
		}
	}

	while(i<K1)
	{
		exp[K] = exps1[i];
		coe[K] = coes1[i];
		K++;
		i++;
	}

	while(j<K2)
	{
		exp[K] = exps2[j];
		coe[K] = coes2[j];
		K++;
		j++;
	}
	printf("%d",K);
	for (i=0;i<K;i++)
		printf(" %d %.1f",exp[i],coe[i]);
	
	printf("\n");
	return 0;
}

  

posted @ 2013-07-02 15:28  summer_zhou  阅读(251)  评论(0)    收藏  举报