甲级PAT 1009 Product of Polynomials

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

题目要求: 

计算两个多项式的乘积。例如A = a*x^1+b*x^2 ; B = c*x^1+d*x^5+e*x^6

A*B = (a*c)x^2+(a*d)x^6+(a*e)x^7+(b*c)x^3+(b*d)x^7+(b*e)x^8 = (a*c)x^2+(b*c)x^3+(a*d)x^6+(a*e+b*d)x^7+(b*e)x^8 

如果系数乘积为0就不用输出了。

输出格式,指数要按从大到小的顺序。

解题思路:

刚开始第一种思路是用数组下标来当指数,存储的值用来当系数,但是这样需要1000*1000*sizeof(float)大小的数组,所以肯定不行。

写一个单项式的结构体。因为每一个多项式由最多不超过10个单项式组成,两个多项式乘积后最多的单项式不超过100个。用一个多项式的每一项依次去乘以另个一个多项式的每一项要写两重循环。每一次乘积就是指数之和以及系数的乘积。用于存储乘积后的多项式在存入时需要判断这个指数是否已经存在,存在的话直接将系数加起来,不存在的话将该项存入。最后输出的时候要按指数从大到小排序输出。这里写一下结构体比较方法就好了。

注意:

最后输出的时候,因为有存在系数之和为0的情况,所以,要先循环计算一共有多少个系数不为0的指数,然后把这些数据输出。

完整代码:

#include<iostream>
#include<algorithm>
#include<iomanip>
using namespace std;
#define maxsize 1001

typedef struct monomial{
	int exp;//指数
	float coe; //系数 
}mon;


mon mon1[10];
mon mon2[10];
mon mon3[101];

bool comp(mon &mon1,mon &mon2){
	return mon1.exp>mon2.exp;
}


int main(){
	int K1,K2,i,j,k,exp,len=0,num=0;
	float coe;
	cin>>K1;
	for(i=0;i<K1;i++){
		cin>>mon1[i].exp>>mon1[i].coe; 
	}
	cin>>K2;
	for(i=0;i<K2;i++){
		cin>>mon2[i].exp>>mon2[i].coe; 
	}
	for(i=0;i<K1;i++){
		for(j=0;j<K2;j++){
			exp = mon1[i].exp+mon2[j].exp;
			coe = mon1[i].coe * mon2[j].coe;
			for(k=0;k<len;k++){
				if(mon3[k].exp == exp){
					mon3[k].coe += coe;
					break;
				}
			}
			if(k==len){
				mon3[len].exp = exp;
				mon3[len++].coe = coe;
			}
		}
	}
	sort(mon3,mon3+len,comp);
	for(i=0;i<len;i++){
		if(mon3[i].coe!=0){
			num++;
		}
	}
	cout<<num;
	for(i=0;i<len;i++){
		if(mon3[i].coe!=0){
			cout<<" "<<mon3[i].exp<<" "<<fixed<<setprecision(1)<<mon3[i].coe;
		}
	}	
	
	
	return 0;
}

 

点赞