數據結構實驗之查找七:線性之哈希表 SDUT 3379

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

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

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