Problem Description
根據給定的一系列整數關鍵字和素數p,用除留餘數法定義hash函數H(Key)=Key%p,將關鍵字映射到長度爲p的哈希表中,用線性探測法解決衝突。重複關鍵字放在hash表中的同一位置。
Input
連續輸入多組數據,每組輸入數據第一行爲兩個正整數N(N <= 1500)和p(p >= N的最小素數),N是關鍵字總數,p是hash表長度,第2行給出N個正整數關鍵字,數字間以空格間隔。
Output
輸出每個關鍵字在hash表中的位置,以空格間隔。注意最後一個數字後面不要有空格。
Example 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
Example Output
1 1 1 1 1 4 0 1 3 4 0 1 2 4 0 1 2 0
Hint
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
int has[1505];
int loc[1505];
int main()
{
int n,p;
while(cin>>n>>p)
{
memset(has,-1,sizeof(has));
for(int i = 0; i < n ; ++i)
{
int key;
cin>>key;
for(int j = 0; j < n; ++j)
{
int t = ((key%p)+j)%p;
if(has[t] == -1)
{
has[t] = key;
loc[i] = t;
break;
}
else if(has[t] == key)
{
loc[i] = t;
break;
}
}
}
for(int i = 0; i < n; ++i)
{
if(i)
cout<<' ';
cout<<loc[i];
}
cout<<endl;
}
return 0;
}