1009. Product of Polynomials (25)
Problem Descrpition
This time, you are supposed to find A*B where A and B are two polynomials.
Input
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
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之后A×B应该没问题的,,结果还是踩坑,特此记录!
exponents :指数
coefficients :系数
另外我是用map来存结果,所以每次更新后,若值为0,则需要将这个元素删除
Code
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <queue>
#include <map>
#include <string>
using namespace std;
map<int,double> arr1,arr2,res;
int main()
{
int n,a;
double x;
cin>>n;
while(n--)
{
cin>>a>>x;
arr1[a]=x;
}
cin>>n;
while(n--)
{
cin>>a>>x;
arr2[a]=x;
}
map<int,double>::iterator i,j;
for(i=arr1.begin();i!=arr1.end();i++)
{
for(j=arr2.begin();j!=arr2.end();j++)
{
int key=i->first+j->first;
double val=i->second*j->second;
if(!res[key])
res[key]=val;
else
res[key]+=val;
if(res[key]==0)
{
res.erase(key);
}
}
}
cout<<res.size();
for(map<int,double>::reverse_iterator it=res.rbegin();it!=res.rend();it++)
{
cout<<' '<<it->first;
printf(" %.1f",it->second);
}
return 0;
}