数据结构实验之查找五:平方之哈希表
2016-12-08 11:17
351 查看
Problem Description
给定的一组无重复数据的正整数,根据给定的哈希函数建立其对应hash表,哈希函数是H(Key)=Key%P,P是哈希表表长,P是素数,处理冲突的方法采用平方探测方法,增量di=±i^2,i=1,2,3,...,m-1Input
输入一组测试数据,数据的第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
#include<stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #define MAXNUM 550 typedef struct { int *elem; //存储空间基址 int length; int listsize; }HashSq; int InitialSq(HashSq *L) //初始化哈斯表 { L->elem = (int *)malloc(MAXNUM*sizeof(int)); if(!L->elem) return -1; L->length = 0; L->listsize = MAXNUM; return 1; } int main() { int n,p,i,x,pos,m; HashSq L; InitialSq(&L); while(scanf("%d%d",&n,&p)!=EOF) { for(i = 0;i < p;i++) { L.elem[i] = -1; } for(i = 0;i < n;i++) { scanf("%d",&x); pos = x%p; // printf("******%d\n",pos); if(L.elem[pos]==-1) { L.elem[pos] = x; // printf("%d ",pos); } else { m = sqrt(p); for(int j = 1;j < m;j++) { pos = (x+j*j)%p; // printf(".....*%d\n",pos); if(L.elem[pos]==-1) { L.elem[pos] = x; // printf("%d ",pos); break; } pos = (x-j*j)%p; // printf("..........%d\n",pos); if(L.elem[pos]==-1) { L.elem[pos] = x; // printf("%d ",pos); break; } } } //if(L.elem[pos]==x) if(i!=n-1) printf("%d ",pos); else printf("%d\n",pos); } } return 0; }
相关文章推荐
- 数据结构实验之查找五:平方之哈希表
- 数据结构实验之查找五:平方之哈希表
- 数据结构实验之查找五:平方之哈希表
- 数据结构实验之查找五:平方之哈希表
- 数据结构实验之查找五:平方之哈希表
- 数据结构实验之查找五:平方之哈希表
- 数据结构实验之查找五:平方之哈希表
- 数据结构实验之查找五:平方之哈希表
- 数据结构实验之查找五:平方之哈希表
- 数据结构实验之查找五:平方之哈希表
- 数据结构实验之查找五:平方之哈希表
- 数据结构实验之查找五:平方之哈希表
- 数据结构实验之查找五:平方之哈希表
- 数据结构实验之查找五:平方之哈希表
- 数据结构实验之查找五:平方之哈希表 sdut oj 3377
- 数据结构实验之查找五:平方之哈希表
- 数据结构实验之查找五:平方之哈希表
- 数据结构实验之查找五:平方之哈希表
- 数据结构实验之查找五:平方之哈希表
- 数据结构实验之查找五:平方之哈希表