题目
1009 Product of Polynomials (25 分)
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 N
1
a
N
1
N
2
a
N
2
... N
K
a
N
K
where K is the number of nonzero terms in the polynomial, N
i
and a
N
i
(i=1,2,⋯,K) are the exponents and coefficients, respectively. It is given that 1≤K≤10, 0≤N
K
<⋯<N
2
<N
1
≤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
分析
这道题是一个多项式的乘法,利用map进行遍历即可,也可以使用数组的方法,注意系数为0的情况要被删除!
从这道题里面可以巩固一下map的遍历及自定义排序输出!
代码
#include<iostream>
#include<stdio.h>
#include<map>
using namespace std;
int main(){
map<int,float> m1;
map<int,float,greater<int>> m3;
int n;
cin>>n;
for(int i=0;i<n;i++){
int x;float y;
cin>>x>>y;
m1[x]=y;
}
cin>>n;
for(int i=0;i<n;i++){
map<int,float>::iterator it1=m1.begin();
int x;float y;
cin>>x>>y;
for(;it1!=m1.end();it1++){
int u = it1->first+x;
float v = it1->second*y;
if(m3.find(u)==m3.end()){
m3[u]=v;
}else{
m3[u]+=v;
if(m3[u]==0.0){
m3.erase(u);
}
}
}
}
cout<<m3.size();
map<int,float,greater<int>>::iterator it3=m3.begin();
for(;it3!=m3.end();it3++){
printf(" %d %.1f",it3->first,it3->second);
}
}