數據結構實驗之查找五:平方之哈希表 SDUT 3377

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開始),數據之間以空格間隔,以平方探測方法處理衝突。

Sample Input
4 11
10 6 4 15
9 11
47 7 29 11 9 84 54 20 30
Sample Output
10 6 4 5
3 7 8 0 9 6 10 2 1

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define inf 0x3f3f3f3f

int a[1005], hash[1005], re[1005];

int main()
{
	int n, p, i, j, jj, x;
	while(~scanf("%d %d", &n, &p))
	{
		for(i=0;i<n;i++)
		{
			scanf("%d", &a[i]);
		}
		memset(hash, inf, sizeof(hash));
		for(i=0;i<n;i++)
		{
			x = a[i] % p;
			if(hash[x]==inf)
			{
				hash[x] = a[i];
				re[i] = x;
			}
			else 
			{
				for(j=1; ;j++)
				{
					jj = j * j;
					if(hash[(x + jj)%p]==inf)
					{
						hash[(x+jj)%p] = a[i];
						re[i] = (x+jj)%p;
						break;
					}
					else if(hash[(x - jj)%p]==inf)
					{
						hash[(x-jj)%p] = a[i];
						re[i] = (x-jj)%p;
						break;
					}
				}
			}
		}
		for(i=0;i<n;i++)
		{
			if(i==n-1) printf("%d\n", re[i]);
			else printf("%d ", re[i]);
		}
	}
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章