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
where K is the number of nonzero terms in the polynomial, N
i
and a
N
i
(i=1,2,⋯,K) are the exponents and coefficients, respectively. It is given that 1≤K≤10, 0≤N
K
<⋯<N
2
<N
1
≤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+1000=2000)
#include<iostream>
#include<stack>
using namespace std;
struct Num{
int exp; //指数相加
double coef; //系数相乘
};
Num Poly1[11];
Num Poly2[11];
int K1,K2;
void input()
{
cin>>K1;
for(int i=0;i<K1;i++)
cin>>Poly1[i].exp>>Poly1[i].coef;
cin>>K2;
for(int i=0;i<K2;i++)
cin>>Poly2[i].exp>>Poly2[i].coef;
}
double result[2002]; //其中数组下标代表指数,数组元素存储系数
//注意结果数组C的大小要大于2000,以为A,B中指数的最大值为1000,相乘后的值不大于2000
void Mult()
{
fill(result,result+2002,0);
for(int i=0;i<K1;i++)
for(int j=0;j<K2;j++)
result[Poly1[i].exp+Poly2[j].exp]+=Poly1[i].coef*Poly2[j].coef;
}
void output()
{
stack <int>res;
for(int i=0;i<2002;i++)
if(result[i]!=0) //可能有小于0的系数
res.push(i);
printf("%d",res.size());
if(res.empty()) printf("\n");
while(!res.empty())
{
printf(" %d %.1f",res.top(),result[res.top()]);
res.pop();
}
}
int main()
{
input();
Mult();
output();
}
总结
结构函数可用两个数组替代,多项式储存方式不唯一;