简单哈希

[align=center]简单哈希[/align]
Description
使用线性探测法(Linear Probing)可以解决哈希中的冲突问题,其基本思想是:设哈希函数为h(key) = d, 并且假定哈希的存储结构是循环数组, 则当冲突发生时, 继续探测d+1, d+2…, 直到冲突得到解决.

例如, 现有关键码集为 {47,7,29,11,16,92,22,8,3},

设:哈希表表长为m=11;哈希函数为Hash(key)=key mod 11;采用线性探测法处理冲突。建哈希表如下:

[img]http://dl2.iteye.com/upload/attachment/0105/1102/59e0e5a9-ca37-33cb-8bd9-bd10d457df4e.png[/img]

现在给定哈希函数为Hash(key)= key mod m,要求按照上述规则, 使用线性探测法处理冲突.要求建立起相应哈希表,并按要求打印。

Input

仅有一个测试用例, 第1行为整数n与m(1 <= n, m <= 10000), n代表key的总数, m代表哈希表的长度, 并且令哈希函数为: Hash(key) = key mod m.
接下来n行,每行一个整数,代表一个key。Key与key两两不相同 ( 0 <= key <= 10, 000)。

Output
输出建立好的hash表,比如下表

[img]http://dl2.iteye.com/upload/attachment/0105/1102/59e0e5a9-ca37-33cb-8bd9-bd10d457df4e.png[/img]

应输出

0#11
1#22
2#NULL
3#47
4#92
5#16
6#3
7#7
8#29
9#8
10#NULL
----------------------------
Sample Input
Copy sample input to clipboard
3 5
1
5
6
-----------------------------
Sample Output
0#5
1#1
2#6
3#NULL
4#NULL
-------------------------------
代码如下:

#include<iostream>
using namespace std;

int a[10001];

int Hash(int key,int m)
{
return key%m;
}

int main()
{
int n,m,key;
cin>>n>>m;

for(int j = 0;j < n;j++)
{
cin>>key;
int index = Hash(key,m);

while(1)
{
if(a[index] == '\0')
{
a[index] = key;
break;
}
index=(index+1)%m;
}
}

for(int i = 0;i < m;i++)
{
cout<<i<<"#";
if(a[i]=='\0')
cout<<"NULL"<<endl;
else
cout<<a[i]<<endl;
}

return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值