数据结构实验之查找七:线性之哈希表
Time Limit: 1000MS
Memory Limit: 65536KB
Problem Description
根据给定的一系列整数关键字和素数p,用除留余数法定义hash函数H(Key)=Key%p,将关键字映射到长度为p的哈希表中,用线性探测法解决冲突。重复关键字放在hash表中的同一位置。
Input
连续输入多组数据,每组输入数据第一行为两个正整数N(N <= 1500)和p(p >= N的最小素数),N是关键字总数,p是hash表长度,第2行给出N个正整数关键字,数字间以空格间隔。
Output
输出每个关键字在hash表中的位置,以空格间隔。注意最后一个数字后面不要有空格。
Example 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
Example Output
1 1 1 1 1 4 0 1 3 4 0 1 2 4 0 1 2 0
Hint
Author
xam
#include <bits/stdc++.h>
using namespace std;
int Hash[2222];
int main()
{
int n,p,x;
std::ios::sync_with_stdio(false);
while(cin>>n>>p)
{
memset(Hash,-1,sizeof(Hash));
for(int i=0; i<n; i++)
{
cin>>x;
int t=x%p;
if(Hash[t]==-1)
{
Hash[t]=x;
cout<<t;
}
else
{
bool flag=true;
for(int j=0;j<p;j++)///必须用一个循环判断x是否在Hash中,如最后一组测试数据输入最后一个39,
///如果直接用Hash[t]==x判断,因为Hash[t]此时是24,所以本来应该输出0此时却会输出3,输出错误
{
if(Hash[j]==x)
{cout<<j;flag=false;break;}
}
if(flag==true)
{
while(Hash[t%p]!=-1)
t++;
cout<<t%p;
Hash[t%p]=x;
}
}
if(i!=n-1)
cout<<' ';
else
cout<<endl;
}
}
return 0;
}
///RTA
#include <bits/stdc++.h>
using namespace std;
int Hash[2222],a[2222],b[2222];///a[i]取值范围未给定,可能会超出b[2222]的内存范围,所以不能用数组存储.
int main()
{
int n,m;
std::ios::sync_with_stdio(false);
while(cin>>n>>m)
{
memset(a,0,sizeof(a));
memset(Hash,-1,sizeof(Hash));
memset(b,0,sizeof(b));
for(int i=0; i<n; i++)
cin>>a[i];
for(int i=0; i<n; i++)
{
int t=a[i]%m;
if(Hash[t]==-1)
{b[a[i]]=t;Hash[t]=a[i];}
else
{
int flag=0;
for(int j=0; j<m; j++)
if(Hash[j]==a[i])
{b[a[i]]=j;flag=1;break;}
if(!flag)
{
while(Hash[t%m]!=-1)
t++;
b[a[i]]=t%m;
Hash[t%m]=a[i];
}
}
}
for(int i=0; i<n; i++)
{
if(!i)
cout<<b[a[i]];
else
cout<<' '<<b[a[i]];
}
cout<<endl;
}
return 0;
}