1009. Product of Polynomials (25)
时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue
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
题目大意: A,B是两个多项式,分别给予各自非零项的数目,非零项的指数,底数,要求计算A,B相乘的结果。结果的输出形式和A,B输入形式相同。底数保留小数点后一位。
思路:多项式相乘就是前者每一项乘以后者所有项,底数相乘,指数相加。最后指数相同的进行合并同类项。
坑点:数据范围题目中规定指数小于等于1000,然而实际上开一千多最后两个点过不去,我一狠心开了1万就过去了。。。。。另外要注意对于零项的处理,因为底数可能是负数,合并过程中会使一种指数对应的底数变为0。而要求的输出是非零项的数目。
代码如下:
#include<iostream>
#include<cmath>
#include<iomanip>
using namespace std;
struct node
{
double coeffient;//底数
int exponent;//指数
}a[11],b[11];//多项式A,B
int main()
{
int k1,k2;
cin>>k1;
for(int i=0;i<k1;i++)cin>>a[i].exponent>>a[i].coeffient;
cin>>k2;
for(int i=0;i<k2;i++)cin>>b[i].exponent>>b[i].coeffient;
int num=0;
double result[10010]={0};//下标表示指数,值表示底数
for(int i=0;i<k1;i++)
{
for(int j=0;j<k2;j++)
{
int tem1=a[i].exponent+b[j].exponent;//指数相加
double tem2=a[i].coeffient*b[j].coeffient;//底数相乘
if(!result[tem1]) num++;//出现新的指数,则项数+1
result[tem1]+=tem2;
if(!result[tem1])num--;//出现0项,项数-1
}
}
cout<<num;//非零项数量
for(int j=10000;j>=0;j--)
{
if(result[j])cout<<' '<<j<<' '<<fixed<<setprecision(1)<<result[j];
}
cout<<endl;
}