目录
题目:
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
解题思路:
两个多项式相乘,用第二个多项式的每一项,乘以第一个多项式中的每一项,幂数相同的项系数相加。这里用数组的下标表示多项式幂数,对应的数组值为多项式项系数。
C语言实现:
#include<stdio.h>
int main(int argc, char** argv) {
int k;
float A[1001]={0.0}; //存放第一个序列
float B[2001]={0.0}; //存放结果,结果幂数最高2000
scanf("%d",&k);
int local; //存放幂数
float temp; //存放系数
while(k--){ //存放第一个多项式
scanf("%d%f",&local,&temp);
A[local]=temp;
}
scanf("%d",&k);
while(k--){ //将第二个多项式依次与第一个多项式相乘,时间复杂度O(Nk);
scanf("%d%f",&local,&temp);
for(int i=0;i<1001;++i){
if(A[i]!=0){
B[i+local]+=A[i]*temp; //幂数相加,系数相乘,结果相加。
}
}
}
k=0;
for(int i=0;i<2001;++i){ //统计非零项数
if(B[i]!=0.0){
++k;
}
}
printf("%d",k);
if(k!=0){
printf(" ");
}
for(int i=2000;i>=0&&k>0;--i){
if(B[i]!=0){
printf("%d %.1f",i,B[i]);
--k;
if(k!=0){
printf(" ");
}
}
}
return 0;
}