统计数字出现次数
来源:互联网 发布:导航触摸屏校正软件 编辑:程序博客网 时间:2024/05/22 14:05
Description
某次科研调查时得到了n个自然数,每个数均不超过1500000000(1.5*10^9)。已知不相同的数不超过10000个,现在需要统计这些自然数各自出现的次数,并按照自然数从小到大的顺序输出统计结果。Input
包含多个测试数据,每个包含n+1行:
第1行是整数n,表示自然数的个数。
第2~n+1行每行一个自然数。
1<=n<=200000,每个数均不超过1 500 000 000(1.5*109)Output
对每个测试数据输出m行(m为n个自然数中不相同数的个数),按照自然数从小到大的顺序输出。每行输出两个整数,分别是自然数和该数出现的次数,其间用一个空格隔开。相邻两个测试数据间用一个空行隔开。
Sample Input
Copy sample input to clipboard
8
2
4
2
4
5
100
2
100
Sample Output
2 3
4 2
5 1
100 2
用到的库
map
思路
map<int, int>
前一个int代表数字,后一个代表出现的数字,插进去的时候马上是有序的,如果已经存在,将对应的第二个int的数量加1就行,没有任何的查找
#include <iostream>#include <map>using namespace std;int main() { int num; long long data; int c = 0; while(cin >> num) { if(c != 0) { cout << endl; } else { c = 1; } map<long long, long long> map1; for(int i = 0; i < num; i++) { cin >> data; auto ret = map1.find(data); if(ret == map1.end()) { map1[data] = 1; } else { ret->second++; } } for(auto it = map1.begin(); it != map1.end(); it++) { cout << it->first << " " << it->second << endl; } } return 0;}
阅读全文