PAT甲级1002.

目录

A1002

题目

A1002

样例

输入:

2 1 2.4 0 3.2
2 2 1.5 1 0.5

输出:

3 2 1.5 1 2.9 0 3.2

思路和坑点

  使用map容器存放每一项的指数e和系数c对应关系,合并时候直接在map上操作,然后map逆序遍历,按照指数由大到小输出结果。
  坑点
  处理map时候,如果遇到系数为零的直接剔除,此题的浮点数比较不严格直接可以使用==进行判定。

AC代码

#include<bits/stdc++.h>
using namespace std;
int main(void){
#ifdef ONLINE_JUDGE
#else
    freopen("1.txt","r",stdin);
#endif
    int a,b;
    map<int,double> mp;
    cin>>a;
    for(int i=0;i<a;i++){
        int e;
        double c;
        cin>>e>>c;
        mp[e]=c;
    }
    cin>>b;
    for(int i=0;i<b;i++){
        int e;
        double c;
        cin>>e>>c;
        mp[e]+=c;
        if(mp[e]==0)            //如果系数相加后为0 ,则剔除这一项 
            mp.erase(e);
    }
    cout<<mp.size();
    for(auto it=mp.rbegin();it!=mp.rend();it++){
        printf(" %d %.1f",it->first,it->second);
    }
    return 0;
}