Description
某次科研调查时得到了n个自然数,每个数均不超过1500000000(1.5*109)。已知不相同的数不超过10000个,现在需要统计这些自然数各自出现的次数,并按照自然数从小到大的顺序输出统计结果。
Input
输入文件count.in包含n+1行:
第1行是整数n,表示自然数的个数。
第2~n+1行每行一个自然数。Output
输出文件count.out包含m行(m为n个自然数中不相同数的个数),按照自然数从小到大的顺序输出。每行输出两个整数,分别是自然数和该数出现的次数,其间用一个空格隔开。
Sample Input
8 2 4 2 4 5 100 2 100
Sample Output
2 3 4 2 5 1 100 2
看到要去掉重复项,我很激动了用了set,然后状态一直 红红的一片
,然后我发现了输入的要统计的数字可以很大!数组不能开的那么大,还是老老实实排序后找到不同项时输出好了...
我还是应该要记住不要特别激动一头撞到某个知识点里面去,不行的时候还是要回归普通思路!
【MLE代码】
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <set>
using namespace std;
const int maxn = 2000005;
int a[maxn],b[maxn];
int main()
{
set<int> s;//用set的话数组开不了那么大,内存要超出
set<int>::iterator it;
int n;
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
cin>>n;
for(int i = 0 ; i < n ; i ++)
{
cin>>b[i];
a[b[i]] ++;
}
sort(b,b + n);
for(int i = 0;i < n;i++)
{
s.insert(b[i]);
}
for(it = s.begin(); it != s.end() ; it++)
{
printf("%d %d\n",*it,a[*it]);
}
return 0;
}
【通过代码】
#include <stdio.h>
#include <stdlib.h>
int n;
int a[200000+1];
int cmp(const void *a,const void *b){
return *(int *)a-*(int *)b;
}
int main(){
// freopen("count.in","r",stdin);
// freopen("count.out","w",stdout);
while(scanf("%d",&n)==1){
for (int i=1;i<=n;i++){
scanf("%d",&a[i]);
}
qsort(a+1,n,sizeof(int),cmp);
int cnt=0,s=0;
for (int i=1;i<=n;i++){
if (i==1){
s=a[i];
cnt++;
continue;
}
if (s!=a[i]){
printf("%d %d\n",s,cnt);
s=a[i];
cnt=1;
}
else if (s==a[i]) cnt++;
}
printf("%d %d\n",s,cnt);
}
return 0;
}