Pat(Advanced Level)Practice--1002(A+B For Polynomials)

Pat1002 代码

#include<cstdio>

#define N 1001

int main(int argc,char *argv[])
{
	int exp1[N],exp2[N],exp3[N];
	float coef1[N],coef2[N],coef3[N];
	int K1=0,K2=0,K3=0;
	int i,j;
	scanf("%d",&K1);
	for(i=0;i<K1;i++)
		scanf("%d%f",&exp1[i],&coef1[i]);
	scanf("%d",&K2);
	for(j=0;j<K2;j++)
		scanf("%d%f",&exp2[j],&coef2[j]);
	i=j=0;
	while(i<K1&&j<K2)
	{
		if(exp1[i]<exp2[j])
		{
			exp3[K3]=exp2[j];
			coef3[K3]=coef2[j];
			j++;
			K3++;
		}
		else if(exp1[i]==exp2[j])
		{
			if(coef1[i]+coef2[j]==0)
			{
				i++;
			    j++;
			}
			else
			{
				coef3[K3]=coef1[i]+coef2[j];
				exp3[K3]=exp1[i];
				i++;
				j++;
				K3++;
			}
		}
		else
		{
			exp3[K3]=exp1[i];
			coef3[K3]=coef1[i];
			K3++;
			i++;
		}
	}
	if(i==K1)
		for(;j<K2;j++)
		{
			exp3[K3]=exp2[j];
			coef3[K3]=coef2[j];
			K3++;
		}
	if(j==K2)
		for(;i<K1;i++)
		{
			exp3[K3]=exp1[i];
			coef3[K3]=coef1[i];
			K3++;
		}
	printf("%d",K3);
	for(i=0;i<K3;i++)
		printf(" %d %.1f",exp3[i],coef3[i]);
	printf("\n");

	return 0;
}
还有一种简单方法,如下:
#include <stdio.h>
const int N=1000;
void Polynomials()
{
	float ar1[N+1],ar2[N+1],f;
	int k,i,index;
	for(i=0;i<=N;i++) {ar1[i]=0;ar2[i]=0;}
	scanf("%d",&k);
	for(i=0;i<k;i++) 
	{
		scanf("%d%f",&index,&f);
		ar1[index]=f;
	}
	scanf("%d",&k);
	for(i=0;i<k;i++)
	{
		scanf("%d%f",&index,&f);
		ar2[index]=f;
	}
	k=0;
	for(i=0;i<=N;i++)
	{
		ar1[i]+=ar2[i];
		if(ar1[i]!=0) k++;
	}	
	printf("%d",k);
	for(i=N;i>=0;i--)
	{
		if(ar1[i]!=0) printf(" %d %.1f",i,ar1[i]);
	}
 }


int main()
{
	Polynomials();
	return 0;
}

你可能感兴趣的:(编程,C++,算法,STL,pat)