pta--1009 Product of Polynomials (hash)

1009 Product of Polynomials (25)(25 分)

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

For each test case you should output the product 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 up to 1 decimal place.

Sample Input

2 1 2.4 0 3.2
2 2 1.5 1 0.5

Sample Output

3 3 3.6 2 6.0 1 1.6

【分析】题意为每两行一组,每行输入该行多项式,每一项先输指数,再输系数 ,然后输出这两个多项式的乘积的项数以及每一项的指数和系数。方法就是用数组的下标来存储指数,值来存储系数。分别存到两个数组,再将乘积放到另一个数组里。注释掉的为调试用的。

#include<bits/stdc++.h>
using namespace std;
double a[1005],b[1005],c[2005];//下标表示指数,值表示系数 
int main()
{
	int cnt=0,max1=0,max2=0,max3=0;
	int k;
	cin>>k;
	for(int i=0;i<k;i++)
	{
		int x;double y;
		cin>>x>>y;
		a[x]+=y;//	printf("a[%d]=%.1lf\n",x,y);
		if(x>max1)max1=x;
	}
	cin>>k;
	for(int i=0;i<k;i++)
	{
		int x;double y;
		cin>>x>>y;
		b[x]+=y;//	printf("b[%d]=%.1lf\n",x,y);
		if(x>max2)max2=x;
	}
	for(int i=0;i<=max1;i++)
	{
		for(int j=0;j<=max2;j++)
		{
		//	cout<<a[i]<<"×"<<b[j]<<endl;
			if(a[i]!=0&&b[j]!=0)c[i+j]+=a[i]*b[j];
		//	printf("c[%d]=%.1lf\n",i+j,c[i+j]);
			if(i+j>max3)max3=i+j;
		}
	}
	for(int i=0;i<=max3;i++)if(c[i]!=0)cnt++;
	printf("%d",cnt);
	int i=0;
	while(c[i++]==0);
	for(int k=max3;k>=i-1;k--)
	{
		if(c[k])printf(" %d %.1lf",k,c[k]);
	}	
	cout<<endl;
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/qq_38735931/article/details/81672885
今日推荐