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两个多项式,要求他们的乘积。所以要存储两个多项式,我第一时间想到是用一个自定义的结构,后来仔细一想用map应该会更加方便一点。因为用map定义下标的话,相同的下标就可以直接合并了,不需要另外设置flag变量来判断是否存在这个指数是否已经存在。
易错点:
1. 测试点0:需要考虑多项式系数为0时不输出。如下(因为x指数为1的系数为0,所以输出答案中的k==2,且不输出x指数为1的多项式):
输入:
2 1 1 0 -1
2 1 1 0 1输出:
2 2 1.0 0 -1.0
2. 测试点3,4:因为Nk的指数是0-1000所以结果里指数最大应该有2000,定义数组的时候最小应有2001才不至于造成越界。并且要注意输出的时候结果是按照指数由大到小的(如果测试点3是答案错误而不是数组越界的话,可以试着将结果重新排序一下)
代码:
#include<bits/stdc++.h>
using namespace std;
typedef struct Pol{
int fre;// 多项式x的次数
double val;// 多项式x的系数
};
bool cmp(Pol a,Pol b){
return a.fre>b.fre;
}
int flag[2001];//用于判断前面是否已经存在过相同的x次数
int main(){
Pol A[20],B[20];
Pol R[1000];
int k=0;
memset(flag,0,sizeof(flag));//对所有flag进行置零
int K1,K2;
cin>>K1;
for(int i=0;i<K1;i++){//读取多项式A
cin>>A[i].fre>>A[i].val;
}
cin>>K2;
for(int i=0;i<K2;i++){//读取多项式B
cin>>B[i].fre>>B[i].val;
}
for(int i=0;i<K1;i++){//将多项式A,B相乘
for(int j=0;j<K2;j++){
int temp;
temp=A[i].fre+B[j].fre;
if(flag[temp]==0){//若flag为0,说明没有相同的次数,直接并入数组R
flag[temp]=1;
R[k].fre=temp;
R[k].val=A[i].val*B[j].val;
k++;
}
else{
for(int i=0;i<k;i++){
if(R[i].fre==temp){
R[i].val+=A[i].val*B[j].val;
}
}
}
}
}
int num=k;
for(int i=0;i<k;i++){//将系数为0的,在总数量中减去
if(R[i].val==0) num--;
}
cout<<num;
sort(R,R+k,cmp);//对数组R进行由大到小的排序
for(int i=0;i<k;i++){
if(R[i].val==0) continue;//不输出系数为0的多项式
cout<<" "<<R[i].fre<<" "<<setiosflags(ios::fixed)<<setprecision(1)<<R[i].val;
}
return 0;
}