数据结构实验:哈希表
Time Limit: 1000MS Memory Limit: 65536KB
Problem Description
在n个数中,找出出现次数最多那个数字,并且输出出现的次数。如果有多个结果,输出数字最小的那一个。
Input
单组数据,第一行数字n(1<=n<=100000)。
接下来有n个数字,每个数字不超过100000000
Output
出现次数最多的数字和次数。
Example Input
3
1 1 2
Example Output
1 2
Hint
Author
cz
SDUTACM运维技术中心.
#include <bits/stdc++.h>
using namespace std;
struct node
{
int data;
int flag;
int count;
} h[100000+10];
int num=100000000l;
int max_num=0;
void f(int p,int key)
{
if( h[p].data == key) /// 没有发生占用
{
h[p].flag++;
h[p].count++;
}
else if(h[p].flag==0)
{
h[p].flag++;
h[p].count++;
h[p].data=key;
}
else
{
while(h[p].flag!=0 && h[p].data!=key ) ///向后线性移动
{
if( p==(100000-1) )///达到最后一个位置
{
p=0;
}
else p++;
}
if(h[p].flag==0)
{
h[p].flag++;
h[p].count++;
h[p].data=key;
}
else if(h[p].data==key)
{
h[p].flag++;
h[p].count++;
}
}
if(h[p].count >max_num)
{
max_num=h[p].count;
num=key;
}
if(h[p].count == max_num)
{
if(h[p].data < num)
num=h[p].data;
}
}
int main()
{
int n;
cin>>n;///输入个数
for(int i=0; i<100000+10; i++)///初始化
{
h[i].flag=0;
h[i].count=0;
h[i].data=0;
}
for(int i=0; i<n; i++)
{
int t;
cin>>t;
f(t%100000,t);/// 哈希函数(数字对1000000求于)
}
cout<<num<<' '<<max_num<<endl;
return 0;
}
/********
30
86532
846532
8965
7846515
4512312
7845123
78465132
7845123
963
852
789
528451
852
95
8452
84512
798465132
8965
9865412
8465132
98541
8541
5841
8541
8541
8541
6798542
9678542
9867542
852
852 2
*/