天天看點

SDUT-3377 資料結構實驗之查找五:平方之哈希表

資料結構實驗之查找五:平方之哈希表

Time Limit: 400MS  Memory Limit: 65536KB Submit  Statistic  Discuss

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

Example Input

4 11
10 6 4 15
9 11
47 7 29 11 9 84 54 20 30      

Example Output

10 6 4 5
3 7 8 0 9 6 10 2 1
      

Hint

Author

xam

參考:http://blog.csdn.net/code_kk/article/details/50181159
           
#include <bits/stdc++.h>
using namespace std;
int main()
{
    int Hash[1000];
    int n,k,t;
    while(cin>>n>>k)
    {
        memset(Hash, 0, sizeof(Hash));
        for(int i=0; i<n; i++)
        {
            int x;
            cin>>x;
            t = x % k;
            if(Hash[t] == 0)
            {
                Hash[t]=1;
                cout<<t;
            }
            else //題意中已說明無重複資料
            {
                for(int j=1; j<=k-1; j++)
                {
                    if(Hash[(t + j*j)%k] == 0)//注意處理沖突的方法
                    {
                        cout<<(t + j*j)%k;
                        Hash[(t + j*j)%k]=1;
                        break;
                    }
                    else if(Hash[(t - j*j)%k] == 0)
                    {
                        cout<<(t - j*j)%k;
                        Hash[(t - j*j)%k]=1;
                        break;
                    }
                }
            }
            if(i == n-1)
                cout<<endl;
            else
                cout<<" ";
        }
    }
    return 0;
}

           

繼續閱讀