1. 程式人生 > >資料結構實驗之查詢七:線性之雜湊表

資料結構實驗之查詢七:線性之雜湊表

Time Limit: 1000 ms Memory Limit: 65536 KiB

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 Hint Source xam

#include <iostream>
using namespace std;

int const len = 1505;
int main()
{
    int n, p;
    while (cin >> n >> p)
    {
        /*int a[25];
        for (int i = 0; i < n; i++)
            cin >> a[i];*/
int a[len]; int *hash = new int[len](); for (int i = 0; i < n; i++) { int d = 0; cin >> a[i]; int t = a[i] % p; if (!hash[t])//位置為空,就把數存入 { hash[t] = a[i]; cout << t; } else
//不為空,存在衝突,開始線性探測 { //線性探測 bool visit; int tp;//儲存位置記錄 while (hash[(t + d) % p])//開始探測不為空的位置 { visit = false; if (hash[(t + d) % p] == a[i])//找到已經存在的位置 { tp = (t + d) % p; visit = true; break;//找出後必須立即跳出 } d++;//線性尋找 } //經過while探測後,找到為空的位置 hash[(t + d) % p] = a[i]; if (visit)//已經存在輸出存在的 cout << tp; else//不存在,輸出新的位置 cout << (t + d) % p; } if (i == n - 1) cout << endl; else cout << " "; } } system("pause"); return 0; }