您的位置:首页 > 理论基础 > 数据结构算法

【除留余数法定义hash函数+线性探测法解决hash冲突】数据结构实验之查找七:线性之哈希表

2017-12-17 16:29 375 查看
Think:

1知识点:除留余数法定义hash函数+线性探测法解决hash冲突

数据结构实验之查找七:线性之哈希表

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

以下为Accepted代码

#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

int rec[2014], book[2014];

int hash_id(int x, int p);

int main(){
int n, p, x, i;
while(~scanf("%d %d", &n, &p)){
memset(rec, -1, sizeof(rec));
for(i = 0; i < n; i++){
scanf("%d", &x);
book[i] = hash_id(x, p);
}
for(i = 0; i < n; i++){
printf("%d%c", book[i], i == n-1? '\n': ' ');
}
}
return 0;
}
int hash_id(int x, int p){
int id;
id = x%p;
if(rec[id] == -1 || rec[id] == x){
rec[id] = x;
}
else {
while(true){
id++;
id %= p;
if(rec[id] == -1 || rec[id] == x){
rec[id] = x;
break;
}
}
}
return id;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息