题解 | #合并表记录#
合并表记录
https://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201
#include <iostream>
#include <map>
using namespace std;
int main() {
int cnt;
cin>>cnt;
map<int,int> map1;
int a,b;
for(int i=0;i<cnt;i++)
{
cin>>a>>b;
map1[a]+=b;
}
for(map<int,int>::iterator it = map1.begin();it!=map1.end();it++)
cout<<it->first<<" "<<it->second<<endl;
}
// 64 位输出请用 printf("%lld")
从题目中就可以看出来,该题目的要求和STL中的map十分相似,故定义一个map,然后将key值读入,int的value默认为0,故直接使用+=,遇到相同的数据,会自动合并,输入完成后,使用一个for循环将map的key和value按格式输出即可。
查看2道真题和解析