1009. Product of Polynomials (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 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 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
 
  

思路

要求计算A*B的结果,都是多项式,有小数,考虑double型

开一个大小为1001的double A数组,下标代表指数,数组里的内容是系数,再开一个大小为2001的double ans数组,(A、B两个多项式相乘指数最大的项可以达到2000)读取B的每一项因子时,与A的所有项想乘,将答案存储在ans里。

C++:

#include "cstdio"
#include "iostream"

using namespace std;

int main(){
	int k1,k2,n1,n2,cnt=0;
	double arr[1001]={0.0},ans[2001]={0.0},tempB;

	cin>>k1;//A的多项式个数
	for(int i=0;i<k1;i++){
		cin>>n1;//A指数
		cin>>arr[n1];//arr[n1]里存放系数
	}

	cin>>k2;//B的多项式个数
	for(int i=0;i<k2;i++){
		cin>>n2;//B指数
		cin>>tempB;
		for(int j=0;j<=1000;j++){
				ans[n2+j]+=arr[j]*tempB;//B*A的每一项存在ans里
		}
	}

	for (int i=2000;i>=0;i--)
	{
		if(ans[i]!=0)cnt++;
	}
	cout<<cnt;
	for(int i=2000;i>=0;i--){
		if(ans[i]!=0){
		cout<<" "<<i<<" ";
		printf("%.1lf",ans[i]);
		}
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/ysq96/article/details/79843137