哈希 --- 线性探测法

Constraints

Time Limit: 1 secs, Memory Limit: 256 MB

Description

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

例如现有关键码集为 {477291116922283}

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

 

0

1

2

3

4

5

6

7

8

9

10

11

22

 

47

92

16

3

7

29

8

 

 

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

Input

 仅有一个测试用例1行为整数nm1 <= n, m <= 10000), n代表key的总数, m代表哈希表的长度并且令哈希函数为Hash(key) = key mod m.

接下来n行,每行一个整数,代表一个keyKeykey两两不相同 ( 0 <= key <= 10, 000)

Output

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

0

1

2

3

4

5

6

7

8

9

10

11

22

 

47

92

16

3

7

29

8

 

 

应输出

0#11

1#22

2#NULL

3#47

4#92

5#16

6#3

7#7

8#29

9#8

10#NULL

Sample Input

3 5
1
5
6

Sample Output

0#5
1#1
2#6
3#NULL
4#NULL

初学哈希,水一题。

#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
int main()
{
    int n,m;
    int a,b;
    int num[10001];
    memset(num,0,sizeof(num));
    cin>>n>>m;
    while(n--)
    {
        cin>>a;
        b=a%m;
        if(!num[b])
            num[b]=a;
        else
            while(num[b])
            {
                b++;
                b%=m;
            }
            num[b]=a;
    }
    for(int i=0;i<m;i++)
    {
        if(!num[i])
            cout<<i<<"#NULL"<<endl;
        else cout<<i<<"#"<<num[i]<<endl;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/crazyacking/p/3757386.html