SDUT E - 資料結構實驗之查詢五:平方之雜湊表
阿新 • • 發佈:2020-12-09
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
Output
10 6 4 5
3 7 8 0 9 6 10 2 1
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n,p;
while(~scanf("%d %d",&n,&p))
{
int a[1010],has[1010]= {0};
for(int i=0; i<n; i++)
{
scanf ("%d",&a[i]);
}
for(int i=0; i<n; i++)
{
int d=a[i]%p;
if(has[d]==0)
{
has[d]=a[i];
a[i]=d;
}
else
{
for(int j=1;; j++)
{
int k=j*j;
if(has[(d+k)%p]==0)
{
has[(d+k)%p]=a[i];
a[i]=(d+k)%p;
break;
}
else if(has[(d-k)%p]==0)
{
has[(d-k)%p]=a[i];
a[i]=(d-k)%p;
break;
}
}
}
}
for(int i=0; i<n-1; i++)
{
cout<<a[i]<<" ";
}
cout<<a[n-1]<<endl;
}
return 0;
}