PAT-1078 Hashing

1078 Hashing (25)(25 分)

The task of this problem is simple: insert a sequence of distinct positive integers into a hash table, and output the positions of the input numbers. The hash function is defined to be "H(key) = key % TSize" where TSize is the maximum size of the hash table. Quadratic probing (with positive increments only) is used to solve the collisions.

Note that the table size is better to be prime. If the maximum size given by the user is not prime, you must re-define the table size to be the smallest prime number which is larger than the size given by the user.

Input Specification:

Each input file contains one test case. For each case, the first line contains two positive numbers: MSize (<=10^4^) and N (<=MSize) which are the user-defined table size and the number of input numbers, respectively. Then N distinct positive integers are given in the next line. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print the corresponding positions (index starts from 0) of the input numbers in one line. All the numbers in a line are separated by a space, and there must be no extra space at the end of the line. In case it is impossible to insert the number, print "-" instead.

Sample Input:

4 4
10 6 4 15

Sample Output:

0 1 4 -

 注意hash表的长度可能大于10^4,定义时MAX要比10^4大,具体大多少,要看10^4附近质数的密度,由下表知差不多10%。

    另外二次探测失败的处理是通过次数是否超过hash表大小(MAX)来判断,超过MAX次二次探测都失败就判断为表满了,参见wiki上Quadratic Probing的插入算法。

    证明方法也很简单,设表大小为S,当二次探测到第S次(仅考虑正向,负向同理),即“原位置+\large {S^{2}} ”处时,(原位置+\large \bg_black \large {S^{2}})%S==原位置,第S+i(i>0)次探测的结果为  (原位置+\large (S+i)^{2})%S==(原位置+\large i^{2})%S,结果同第i次探测。

 

    补充:当hash表大小可写为形如4*k+3(k为正整数)的质数时,二次探测法可以探查完整个空间。一般情况下,二次探测法可探测到至少一半的空间。

#include<stdio.h>
#include<algorithm>
using namespace std;
#define MAX 11001

int msize,n;
int hasht[MAX];
bool prime[MAX];
int size;

int insert(int v){
	int h=v%size;
	int i=1,t=h;
	while(hasht[t]!=-1){
		if(i>MAX)
			return -1;
		t=h+i*i;
		t=t%size;
		i++;
	}
	hasht[t]=v;
	return t;
}
int main(){
	scanf("%d %d",&msize,&n);

	fill(hasht,hasht+MAX,-1);
	fill(prime,prime+MAX,true);
	prime[0]=prime[1]=false;
	for(int i=2;i<MAX;i++){
		if(prime[i]){
			for(int j=i+i;j<MAX;j+=i)
				prime[j]=false;
		}
	}
	size=msize;
	for(;!prime[size];size++)
		;
	int t;
	scanf("%d",&t);
	int h=insert(t);
	if(h==-1) printf("-");
	else printf("%d",h);
	for(int i=1;i<n;i++){
		scanf("%d",&t);
		int h=insert(t);
		if(h==-1) printf(" -");
		else printf(" %d",h);
	}
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值