1009 Product of Polynomials (25 分)
This time, you are supposed to find where and 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:
…
where is the number of nonzero terms in the polynomial, and () are the exponents and coefficients, respectively. It is given that , .
Output Specification:
For each test case you should output the product of and 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
题目解读:多项式乘法,输入两个多项式,输出它们乘积的有效项数及结果。
解题思路:仍旧用数组去存储多项式,数组下标表示次数,存一个数组,另一个数组边读边乘,这里要注意把结果的数组开大一点,因为多项式的次数最大为1000,那么如果是两个1000相乘就会是1000+1000=2000,所以结果数组要大一倍。
AC代码
#include <iostream>
using namespace std;
double a[1005],ans[2010];
int main(int argc, const char * argv[]) {
int tempa,tempb;
int max = 0;
int amax = 0;
int cnt = 0;
fill(a,a+1005,0);
fill(ans,ans+1005,0);
scanf("%d",&tempa);
for( int i = 0 ; i < tempa ; i ++ ){
int tempk;
scanf("%d",&tempk);
scanf("%lf",&a[tempk]);
if( tempk > amax )
amax = tempk;
}
scanf("%d",&tempb);
for( int i = 0 ; i < tempb ; i ++ ){
int tempk;
double tempnow;
scanf("%d %lf",&tempk,&tempnow);
for( int j = 0 ; j <= amax ; j ++ ){
if( a[j] == 0 )continue;
else{
int ansk = tempk+j;
double ansnow = tempnow*a[j];
ans[ansk] += ansnow;
if( ansk > max )
max = ansk;
}
}
}
for(int i = max ; i >= 0 ; i -- ){
if( ans[i] != 0 )
cnt++;
}
printf("%d",cnt);
for( int i = max ; i >= 0 ; i -- ){
if( ans[i] != 0 ){
printf(" %d %.1f",i,ans[i]);
cnt--;
}
}
return 0;
}
0 条评论