1009 Product of Polynomials (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
解题思路:
1.多项式乘法,和加法类似,最简单明了的方法就是依次读入两个多项式,用两个for循环遍历其中每个式子,指数相加,系数相乘,得到新的多项式。
2.先遍历多项式中的非零项统计个数,再从后向前输出非零项的指数(数组下标),系数(数组的值)。
#include<cstdio>
const int maxn=2001;
double a[maxn]={0.0},b[maxn]={0.0},c[maxn]={0.0};
int main(){
int k1,k2,exp;
double cof;
scanf("%d",&k1);
for(int i=0;i<k1;i++){
scanf("%d %lf",&exp,&cof);
a[exp]=cof;
}
scanf("%d",&k2);
for(int i=0;i<k2;i++){
scanf("%d %lf",&exp,&cof);
b[exp]=cof;
}
for(int i=0;i<maxn;i++) {
if(a[i]!=0.0){
for(int j=0;j<maxn;j++){
if(b[j]!=0.0){
exp=i+j;
cof=a[i]*b[j];
c[exp]+=cof;
}
}
}
}
int cnt=0;
for(int i=0;i<maxn;i++){
if(c[i]!=0.0)
cnt++;
}
printf("%d",cnt);
for(int i=maxn-1;i>=0;i--){
if(c[i]!=0.0)
printf(" %d %.1lf",i,c[i]);
}
return 0;
}
#include<cstdio>
const int maxn=2001;
double a[maxn];
struct poly{
int exp;
double cof;
}poly[1001];
int main(){
int n1,n2;
int cut=0;
//输入第一行
scanf("%d",&n1);
for(int i=0;i<n1;i++){
scanf("%d %lf",&poly[i].exp ,&poly[i].cof);
}
//输入第二行,同时进行A+B操作
scanf("%d",&n2);
int e;
double k;
for(int i=0;i<n2;i++){
scanf("%d %lf",&e,&k);
for(int j=0;j<n1;j++){
a[e+poly[j].exp ]+=(k*poly[j].cof );
}
}
for(int i=0;i<2001;i++){
if(a[i]!=0.0)
cut++;
}
printf("%d",cut);
for(int i=2000;i>=0;i--){
if(a[i]!=0.0){
printf(" %d %.1f",i,a[i]);
}
}
return 0;
}
本文介绍了一种解决多项式乘法问题的算法实现方法,通过遍历输入的两个多项式,利用双重循环完成指数相加和系数相乘的操作,最终输出结果遵循特定格式。
1175

被折叠的 条评论
为什么被折叠?



