PAT Advanced 1002 A+B for Polynomials (25 分)(隐藏条件,多项式的系数不能为0)

时间:2025-01-07 13:37:02

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 sum 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 to 1 decimal place.

Sample Input:

2 1 2.4 0 3.2
2 2 1.5 1 0.5

Sample Output:

3 2 1.5 1 2.9 0 3.2
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct poly{
int expo;
double coef;
};
bool cmp(poly po1,poly po2){
if(po1.expo>po2.expo) return true;
return false;
}
int main(){
/**
注意点:
1.先指数,后系数
2.题意没有注明是否是递降的多项式,所以当做递降的来试试
**/
/**输入数据*/
int T;poly temp;
vector<poly> vec1;
vector<poly> vec2;
vector<poly> res;
cin>>T;
while(T--){
cin>>temp.expo;
cin>>temp.coef;
vec1.push_back(temp);
}
cin>>T;
while(T--){
cin>>temp.expo;
cin>>temp.coef;
vec2.push_back(temp);
}
/**排序,题意没说是有序的*/
sort(vec1.begin(),vec1.end(),cmp);
sort(vec2.begin(),vec2.end(),cmp);
/**计算*/
int i=,j=;
while(true){
if(vec1[i].expo==vec2[j].expo){
poly temp;
temp.expo=vec1[i].expo;
temp.coef=vec1[i].coef+vec2[j].coef;
if(temp.coef!=) res.push_back(temp);
/**coef不为0时相加!!!!!*/
i++;j++;
}else if(vec1[i].expo>vec2[j].expo){
res.push_back(vec1[i]);
i++;
}else{
res.push_back(vec2[j]);
j++;
}
if(i==(vec1.size())){
while(j!=(vec2.size())){
res.push_back(vec2[j]);
j++;
}
break;
}
if(j==(vec2.size())){
while(i!=(vec1.size())){
res.push_back(vec1[i]);
i++;
}
break;
}
if(i==(vec1.size())&&j==(vec2.size())){
break;
}
}
cout<<res.size();
for(int i=;i<res.size();i++){
printf(" %d %.1f",res[i].expo,res[i].coef);
/**注意浮点数应该是一位小数!!!!!*/
}
system("pause");
return ;
}

逻辑正确,出现了大量错误:

1.系数不为0相加未考虑

2.浮点数为一位小数未考虑

考试时应该注意