
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 (,) are the exponents and coefficients, respectively. It is given that 1, 0.
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
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct poly{
int expo;
double coef;
};
void add(vector<poly>& vec,poly po){
for(int i=;i<vec.size();i++){
if(vec[i].expo==po.expo){
vec[i].coef+=po.coef;
if(vec[i].coef==){
vec.erase(vec.begin()+i);
/**这边需要判断0多项式,进行erase掉*/
}
return;
}
}
if(po.coef!=) vec.push_back(po);
}
bool cmp(poly p,poly p2){
return p.expo>p2.expo;
}
int main(){
/**
* 注意点
* 1.保留一位小数
*/
int M,N;vector<poly> res;
cin>>M;
poly p[M];
for(int i=;i<M;i++){
cin>>p[i].expo>>p[i].coef;
}
cin>>N;
poly p2[N];
for(int i=;i<N;i++){
cin>>p2[i].expo>>p2[i].coef;
}
for(int i=;i<M;i++){
for(int j=;j<N;j++){
poly temp;
temp.expo=p[i].expo+p2[j].expo;
temp.coef=p[i].coef*p2[j].coef;
add(res,temp);
}
}
/**这边需要sort一下*/
sort(res.begin(),res.end(),cmp);
cout<<res.size();
for(int i=;i<res.size();i++){
printf(" %d %.1f",res[i].expo,res[i].coef);
}
system("pause");
return ;
}
需要记住vector进行删除元素,用的是erase(iter*)