注意点:系数为0,则不输出,例:

其中-1和1相加为0,则在输出时避免这一项,而且要注意结果的K值,不要包括这一项,
思路,利用结构体存储系数和指数,然后利用两个数组分别存储两个输入,循环查找指数相同项,把它们的系数相加,然后判断是否为0,如果不为0则放入结果数组中,然后将它们的系数设为一个特殊的值(就是随便想的一个值),最后,再进行一次循环判断该项的系数是否为特殊值,不为特殊值则放入结果数组(设置特殊值就是用于跳过已经用于系数相加的项,并且避免麻烦的删除),最后先按指数从大到小的方式进行排序,然后将结果输出,先输出结果数组的长度,然后以空格指数空格系数的方式输出结果
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 (i=1,2,⋯,K) are the exponents and coefficients, respectively. It is given that 1≤K≤10,0≤NK<⋯<N2<N1≤1000.
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 <bits/stdc++.h>
using namespace std;
struct poly{
int ex;
double co;
};
bool cmp(poly a,poly b){
return a.ex>b.ex;
}
int main(){
int k1,k2;
poly po;
cin>>k1;
vector<poly> v1(k1);
for(int i=0;i<k1; i++){
cin>>v1[i].ex>>v1[i].co;
}
cin>>k2;
vector<poly> v2(k2),res;
for(int i=0;i<k2; i++){
cin>>v2[i].ex>>v2[i].co;
}
for(int i=0;i<k1;i++){
for(int j=0;j<k2;j++){
if(v1[i].ex==v2[j].ex){
po.ex = v1[i].ex;
po.co = v1[i].co+v2[j].co;
if(po.co!=0)res.push_back(po);
v1[i].co=-1.129;
v2[j].co=-1.129;
break;
}
}
}
for(int i=0;i<k1;i++){
if(v1[i].co!=-1.129)res.push_back(v1[i]);
}
for(int i=0;i<k2;i++){
if(v2[i].co!=-1.129)res.push_back(v2[i]);
}
cout<<res.size();
sort(res.begin(),res.end(),cmp);
for(int i=0;i<res.size();i++){
printf("%s%d%s%.1f"," ",res[i].ex," ",res[i].co);
}
}
该博客详细解析了PAT甲级编程竞赛中1002题——多项式求和的问题。内容包括输入输出规格,易错点提示,以及解题思路。重点在于如何处理系数为0的情况,以及通过结构体存储系数和指数,避免重复项的错误。博主建议先对输入的多项式进行处理,然后对相同指数的项相加,排除和为0的项,最后按指数降序排列并输出结果。
250

被折叠的 条评论
为什么被折叠?



