华为机试在线训练-牛客网(5)合并表记录

来源:互联网 发布:网络规划设计师 必过 编辑:程序博客网 时间:2024/05/16 01:30

题目描述

数据表记录包含表索引和数值,请对表索引相同的记录进行合并,即将相同索引的数值进行求和运算,输出按照key值升序进行输出。


输入描述:

先输入键值对的个数然后输入成对的index和value值,以空格隔开



输出描述:

输出合并后的键值对(多行)


输入例子:
40 10 21 23 4

输出例子:
0 31 23 4

这题对于C++应该是用map最简单,key-value键值对典型符合map容器的特点。
对于这题,按key升序来降低了难度,因为map默认按key升序:
int main(){    int num=0;    int key=0,value=0;    map<int,int> dataMap;    cin>>num;    for(int i=0;i<num;i++)    {        cin>>key;        cin>>value;        if(dataMap[key])            dataMap[key]+=value;        else            dataMap[key]=value;    }    for(auto e:dataMap){        cout<<e.first<<" "<<e.second<<endl;    }    return 0;}
如果此题改为:
按照key降序排列,或者按照value升序排列等类似的要求
用map砸破?
不能直接使用sort,因为sort参数要求随机访问迭代器,介绍个一般的方法:使用vector<pair<>>将map元素存进去,自定义比较函数(根据条key或value的升序或降序条件),然后使用sort排序
int cmpByValue(const pair<int,int> &x,const pair<int,int> &y){    return x.second>y.second;//以value降序为例}  int main(){    int num=0;    int key=0,value=0;    map<int,int> dataMap;    cin>>num;    for(int i=0;i<num;i++)    {        cin>>key;        cin>>value;        if(dataMap[key])            dataMap[key]+=value;        else            dataMap[key]=value;    }    vector<pair<int ,int> > vec_mapData;    for(auto it=dataMap.begin();it!=dataMap.end();it++){            vec_mapData.push_back(*it);    }    sort(vec_mapData.begin(),vec_mapData.end(),cmpByValue);    for(auto e:dataMap){        cout<<e.first<<" "<<e.second<<endl;    }    return 0; }





0 0
原创粉丝点击