数据结构实验之查找五:平方之哈希表
Time Limit: 400MS
Memory Limit: 65536KB
Problem Description
给定的一组无重复数据的正整数,根据给定的哈希函数建立其对应hash表,哈希函数是H(Key)=Key%P,P是哈希表表长,P是素数,处理冲突的方法采用平方探测方法,增量di=±i^2,i=1,2,3,...,m-1
Input
输入包含多组测试数据,到 EOF 结束。
每组数据的第1行给出两个正整数N(N <= 500)和P(P >= 2N的最小素数),N是要插入到哈希表的元素个数,P是哈希表表长;第2行给出N个无重复元素的正整数,数据之间用空格间隔。
Output
按输入数据的顺序输出各数在哈希表中的存储位置 (hash表下标从0开始),数据之间以空格间隔,以平方探测方法处理冲突。
Example Input
4 11
10 6 4 15
9 11
47 7 29 11 9 84 54 20 30
Example Output
10 6 4 5
3 7 8 0 9 6 10 2 1
Hint
/*-------------------------
Name:数据结构实验之查找五:平方之哈希表
Author:Mr.z
Time:2016-12-10
---------------------------*/
#include <iostream>
#include <string.h>
#include <math.h>
using namespace std;
#define INF 0x3f3f3f3f
int Key[10021],n,ADDR[100021];
typedef struct {
int elem[502],count;
}HashTable;
void InitHashTable( HashTable &H){
memset(H.elem,INF,sizeof(H.elem));
H.count=0;
}
void Insert(HashTable &H){
int addr,j=0;
cin >> H.count;
while(n--){
int i=1,f=1;
cin >> Key[j++];
addr=Key[j-1]%H.count;
while(H.elem[addr]!=INF){
addr=(Key[j-1]+i*i*f)%H.count;
f=-f;
if (f==1) i++;
}
H.elem[addr]=Key[j-1];
ADDR[j-1]=addr;
}
}
int main(){
while(cin >> n){
int N=n;
HashTable H;
InitHashTable(H);
Insert(H);
for(int i=0;i<N;i++){
cout << ADDR[i];
if(i!=N-1) cout << " ";
else cout << endl;
}
}
return 0;
}
/***************************************************
User name: zhxw150244李政
Result: Accepted
Take time: 0ms
Take Memory: 160KB
Submit time: 2016-12-12 12:30:52
****************************************************/
网友评论