2007年分区联赛提高组之一 统计数字

Description

某次科研调查时得到了n个自然数,每个数均不超过1500000000(1.5*109)。已知不相同的数不超过10000个,现在需要统计这些自然数各自出现的次数,并按照自然数从小到大的顺序输出统计结果。

Input

输入包含n+1行;
  第一行是整数n,表示自然数的个数;
  第2~n+1每行一个自然数。

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
Hint

40%的数据满足:1<=n<=1000

80%的数据满足:1<=n<=50000

100%的数据满足:1<=n<=200000,每个数均不超过1500 000 000(1.5*109)

.
.
.
.
.
.
分析
哈希
.
.
.
.
.
程序:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int mo=1555553,h[1555553][2],a[1555553];
int tj=0;

int find(int x)
{
	int w=x%mo,i=0;
	while (i<mo&&h[(w+i)%mo][0]!=-1&&h[(w+i)%mo][0]!=x) i++;
	if (h[(w+i)%mo][0]==x) return (w+i)%mo;
}

void hash(int x)
{
	int w=x%mo,i=0;
	while (i<mo&&h[(w+i)%mo][0]!=-1&&h[(w+i)%mo][0]!=x) i++;
	if (h[(w+i)%mo][0]==-1)
	{
		h[(w+i)%mo][0]=x;
		h[(w+i)%mo][1]++;
		tj++;
		a[tj]=x;
	} else
	if (h[(w+i)%mo][0]==x) h[(w+i)%mo][1]++;
}

int main()
{
	int n;
	scanf("%d",&n);
	memset(h,-1,sizeof(h));
	for (int i=1;i<=n;i++)
	{
		int w;
		scanf("%d",&w);
		hash(w);
	}
	sort(a+1,a+tj+1);
	for (int i=1;i<=tj;i++)
	{
		int w=find(a[i]);
		printf("%d %d
",h[w][0],h[w][1]+1);
	}
	return 0;
}
原文地址:https://www.cnblogs.com/YYC-0304/p/10292792.html