题目:
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
解题思路:
两层循环,分别将两个序列的每个元素的系数相乘、指数相加,最后再将具有相同指数的系数相加合并即可。
注意在此处只需要将系数真正为0的元素去除,而不需要将系数<0.05的元素去除,虽然后者在保留一位小数的情况下显示出来为0.0。
代码:
编译器:C++(g++)
#include <iostream>
#include <vector>
#include <map>
using namespace std;
int main()
{
int k;
cin>>k;
map<int,double> fi;
for(int i=0;i!=k;++i)
{
int t1;
double t2;
cin>>t1>>t2;
fi[t1]=t2;
}
cin>>k;
map<int,double> si;
for(int i=0;i!=k;++i)
{
int t1;
double t2;
cin>>t1>>t2;
si[t1]=t2;
}
map<int,double> result;
for(auto i=fi.begin();i!=fi.end();++i)
{
for(auto j=si.begin();j!=si.end();++j)
{
result[i->first+j->first]+=i->second*j->second;
}
}
//删除系数为0的项
for(auto i=result.begin();i!=result.end();)
{
if(i->second<=1e-15&&i->second>=-1e-15)
i=result.erase(i);
else
++i;
}
cout<<result.size();
cout.flags(ios::fixed);
cout.precision(1);
for(auto i=result.rbegin();i!=result.rend();++i)
{
cout<<" "<<i->first<<" "<<i->second;
}
cout<<endl;
return 0;
}
网友评论