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
结尾无空行
题目大意:
分别给出两个多项式和它们各自拥有的项和系数,计算出两个多项式相乘的结果。
思路:模拟我们平时的多项式乘法运算规则,用第一个多项式里的每一项都与第二个相乘,最后去重化简就可以 了,这里我的思路是用一个book数组来标记有系数的项,遇到相同的项直接加上,最后把这些有系数的项输出即可。
下面我们看代码:
#include <bits/stdc++.h>
using namespace std;
set<pair<int,float>> v1;//多项式1
set<pair<int,float>> v2;//多项式2
int N1,N2;
float book[10001];//标记存储有系数的项
void per1(pair<int,float> p)//这一项与第二个多项式的每一项相乘
{
for(auto i=v2.begin(); i!=v2.end();i++)
{ int x;
double y;
y=p.second*i->second;
x=p.first+i->first;
book[x]+=y;//对应的项系数加上原来的系数
}
}
int main()
{
//freopen("in.txt","r",stdin);
cin>>N1;
for(int i=0;i<N1;i++)//输入第一个多项式
{
pair<int,float> p;
cin>>p.first>>p.second;//输入项和系数
v1.insert(p);
}
cin>>N2;
for(int i=0;i<N2;i++)//输入第一个多项式
{
pair<int,float> p;
cin>>p.first>>p.second;
v2.insert(p);
}
for(auto i=v1.begin(); i!=v1.end();i++)//第一个多项式里的每一项都与第二个相乘
per1(*i);
vector<pair<int,float>> v;
for(int i=10000;i>=0;i--) //从后往前把有系数的存到答案数组v中
{
if(book[i])
{ pair<int,float> p;
p.first=i;
p.second=book[i];
v.push_back(p);
}
}
int len=v.size();
cout<<len;
for(int i=0;i<len;i++)//输出
{
printf(" %d %.1f",v[i].first,v[i].second);
}
return 0;
}