题干:
数据结构实验之查找七:线性之哈希表
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
根据给定的一系列整数关键字和素数p,用除留余数法定义hash函数H(Key)=Key%p,将关键字映射到长度为p的哈希表中,用线性探测法解决冲突。重复关键字放在hash表中的同一位置。
Input
连续输入多组数据,每组输入数据第一行为两个正整数N(N <= 1500)和p(p >= N的最小素数),N是关键字总数,p是hash表长度,第2行给出N个正整数关键字,数字间以空格间隔。
Output
输出每个关键字在hash表中的位置,以空格间隔。注意最后一个数字后面不要有空格。
Sample Input
5 5
21 21 21 21 21
4 5
24 15 61 88
4 5
24 39 61 15
5 5
24 39 61 15 39
Sample Output
1 1 1 1 1
4 0 1 3
4 0 1 2
4 0 1 2 0
代码:
///除留余数法:H(Key)=Key%p
///线性探测法解决冲突:H(Key)=(H(key)+d)%p,(d=0,d++)
# include <bits/stdc++.h>
using namespace std;
int main()
{
int N, p;
while(cin>>N>>p)
{
int z[2000];///记录Hash值
bool flag[2000];///标记Hash数组上是否已经指向某一值
int x[100000];///标记输入的重复数值,开大点
memset(flag,false,sizeof(flag));
memset(x,-1,sizeof(x));
for(int i=0; i<N; i++)
{
int data;
cin>>data;
if(x[data]!=-1)
{
z[i]=x[data];
continue;
}
int t=data%p;
if(!flag[t])
{
x[data]=t;
z[i]=t;
flag[t]=true;
}
else
{
while(flag[t%p])
{
t++;
}
t=t%p;
x[data]=t;
z[i]=t;
flag[t]=true;
}
}
for(int i=0;i<N;i++)
{
cout<<z[i];
if(i==N-1)
cout<<endl;
else
cout<<' ';
}
}
return 0;
}