題目:
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
解題思路:
兩層循環(huán),分別將兩個序列的每個元素的系數(shù)相乘、指數(shù)相加,最后再將具有相同指數(shù)的系數(shù)相加合并即可。
注意在此處只需要將系數(shù)真正為0的元素去除,而不需要將系數(shù)<0.05的元素去除,雖然后者在保留一位小數(shù)的情況下顯示出來為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;
}
}
//刪除系數(shù)為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;
}