PAT Advanced 1009 Product of Polynomials (25 分)(vector删除元素用的是erase)

时间:2023-03-10 02:45:22
PAT Advanced 1009 Product of Polynomials (25 分)(vector删除元素用的是erase)

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​​​​ (,) 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*)