题目重述:
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,A和B是两个多项式。
输入:每一组输入包含一组测试,每个测试包含两行,每行包含格式如下
K N1 aN1 N2 aN2 ... NK aNK
K是非零项的数目,Ni和aNi是指数和系数(1≤K≤10, 0≤NK<⋯<N2<N1≤1000)
输出:一行,A*B所得的多项式
思路分析:之前做过了A+B的问题,参考以前的方法,利用double数组存储,i为下标,数组值为系数,首先输入一个多项式存储到A[i]中,接下来边输入B[i]边计算,每输入一项检测将其与A[i]的非零项指数相加系数相乘,最后遍历整个数组得到非零项个数,然后依次输出。需要注意的是每一个多项式最高指数为1000,所以A*B的最大指数为2000
参考代码:
#include<iostream>
#include <cmath>
#include <iomanip>
using namespace std;
#define MaxN 2001
int main(){
int N1,N2,Count=0;
double A[MaxN],B[MaxN];
for(int i=0;i<MaxN;i++){
A[i] = 0;
B[i] = 0;
}
cin>>N1;
for(int i =0;i < N1;i++){
int exp1;
double coef1;
cin>>exp1>>coef1;
A[exp1]=coef1;
}
cin>>N2;
for(int j =0;j < N2;j++){
int exp2;
double coef2;
cin>>exp2>>coef2;
for(int i=0;i<MaxN;i++)
if(A[i]!=0&&exp2+i<MaxN){
B[exp2+i]+=A[i]*coef2;
}
}
for(int i=0;i<MaxN;i++){
if(B[i]!=0)
Count++;
}
cout<<Count;
for(int i=MaxN-1;i>=0;i--){
if(B[i]!=0)
cout<<" "<<i<<" "<<fixed<<setprecision(1)<<B[i];
}
}