1486. 统计数字
Constraints
Time Limit: 1 secs, Memory Limit: 32 MB
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*10^9)
Output
对每个测试数据输出m行(m为n个自然数中不相同数的个数),按照自然数从小到大的顺序输出。每行输出两个整数,分别是自然数和该数出现的次数,其间用一个空格隔开。
相邻两个测试数据间用一个空行隔开。
Sample Input
8 2 4 2 4 5 100 2 100
Sample Output
2 3 4 2 5 1 100 2
简单统计相同数字,按顺序输出。将输入进行排个序,然后扫描统计即可。这个数虽然范围很大,1.5*10^9,但是没超出32位int范围。简单代码如下:
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
int main()
{
int t;
bool flag=0;
while(cin>>t && t>0)
{
int numbers[t+1];
for(int i=0; i<t; i++)
cin>>numbers[i];
sort(numbers,numbers+t);按要求排个序先
numbers[t] = 0; //为了方便处理,末尾额外加个0
if(flag)<span style="white-space:pre"> </span>//要求中间空行间隔
cout<<endl;
flag = 1;
int count = 1;
for(int i=0; i<t; i++)//扫描判断是否相等并记录
{
if(numbers[i]==numbers[i+1])
count++;
else
{
cout<<numbers[i]<<" "<<count<<endl;
count=1;
}
}
}
//system("pause");
return 0;
}