个人学习记录,代码难免不尽人意
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<cstdio>
#include<iostream>
#include<queue>
#include<map>
using namespace std;
queue<pair<int,double> > q1,q2,q3;
int main(){int k;scanf("%d",&k);for(int i=0;i<k;i++){int n;double a;scanf("%d %lf",&n,&a);q1.push(make_pair(n,a));}scanf("%d",&k);for(int i=0;i<k;i++){int n;double a;scanf("%d %lf",&n,&a);q2.push(make_pair(n,a));}while(!q1.empty()&&!q2.empty()){pair<int,double> p1=q1.front();pair<int,double> p2=q2.front();if(p1.first==p2.first) {q1.pop();q2.pop();double temp=p1.second+p2.second;if(temp!=0)q3.push(make_pair(p1.first,temp));}else{if(p1.first>p2.first){q3.push(p1);q1.pop();}else{q3.push(p2);q2.pop();}}}while(!q1.empty()){pair<int,double> p1=q1.front();q3.push(p1);q1.pop();}while(!q2.empty()){pair<int,double> p2=q2.front();q3.push(p2);q2.pop();}printf("%d",q3.size());while(!q3.empty()){pair<int,double> p3=q3.front();q3.pop();printf(" %d %.1f",p3.first,p3.second);}
}
这道题我采用了队列pair的做法,pair是非常好用的类型,可以代替二元结构体。一开始考虑不周只得了部分分数。需要注意的是,两个多项式相加可能会互相抵消,例如 -x+x=0这样的情况,所以在判断幂数相等之后需要额外判断系数是否相加为0,如果为0则不用入结果队列而是直接将原队列出列即可。