1009 Product of Polynomials
题目描述:
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
思路:
由于两个多项式最高次为1000,因此相乘以后最高次不超过2000,因此定义三个数组,分别存放A,B,AxB的系数,同时,还需要定义两个数组来存放A,B的索引,即多项式的指数。以及两个数字来记录多项式非零项个数
计算的时候,对A,B中所有项进行一个两层的循环,分别计算A中每一项乘以B中每一项的结果
poly[2][p[0][i]+p[1][j]]+=poly[0][p[0][i]]*poly[1][p[1][j]];
注意在上面poly[i]表示第i个多项式的信息,i=0是A,i=1是B,i=2是AxB
同时, p[0][i]
表示第一个多项次的第i项的指数
代码:
#include<stdio.h>
#define MAXK 2001
int main()
{
double poly[3][MAXK]={0};//pay attention to initialize the array
int K[2];int *p[2];
for(int i=0;i<2;i++)
{
scanf("%d",&K[i]);
p[i]=new int[K[i]];
for(int j=0;j<K[i];j++)
{
scanf("%d",&p[i][j]);
scanf("%lf",&poly[i][p[i][j]]);
}
}
for(int i=0;i<K[0];i++)
{
for(int j=0;j<K[1];j++)
{
poly[2][p[0][i]+p[1][j]]+=poly[0][p[0][i]]*poly[1][p[1][j]];
}
}
int count=0;
for(int i=0;i<MAXK;i++)
{
if(poly[2][i]!=0)
count++;
}
printf("%d",count);
for(int i=MAXK-1;i>=0;i--)
{
if(poly[2][i]!=0)
printf(" %d %.1f",i,poly[2][i]);
}
printf("\n");
return 0;
}
git仓库:Product of Polynomials