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
Hint
Source
xam
注:
本题需要注意,重复关键字放在hash表中的同一位置
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
int n, p;
int data, id;
int hash[1505], pos[1505];
while (~scanf("%d %d", &n, &p)){
int top = 0;
memset(hash, -1, sizeof(hash));
for (int i = 0; i < n; i++){
scanf("%d", &data);
id = data%p;
if (hash[id] == -1 || hash[id] == data){ // 该处为空,或数据与该处值相等,都可放入
hash[id] = data;
}
else{
int j = 1;
while (hash[id] != -1 && hash[id] != data){
id = (id+1)%p; // mod p 防止超出表范围
}
hash[id] = data;
}
pos[top++] = id;
}
for (int i = 0; i < top; i++){
if (i != top-1){
printf("%d ", pos[i]);
}
else{
printf("%d\n", pos[i]);
}
}
}
return 0;
}