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

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<stdio.h>
#include<string.h>
#include<stdlib.h>

int n , p ;//關鍵字總數和表長
int hash[15001] ;//hash表
int vis[15001] ; //記錄某個位置是否被佔用
int count ; //增量
int cmd  ;//記錄hash值
int a[15001] ;

void hash1(int x)
{
    int  t = (x+count)%p ;
    if(!vis[t]||x == a[t])
    {
        a[t] = x;
        vis[t] =1 ;
        hash[cmd++] = t;
    }
    else
    {
        count++ ;
        hash1(x) ;
    }
}


int main()
{
    while(~scanf("%d %d",&n,&p))
    {
        int   i ;
        memset(vis,0,sizeof(vis)) ;
        cmd = 0  ;
        for(i =0 ; i<n ; i++)
        {
            int x  ;
            scanf("%d",&x) ;
            count = 0 ;
            hash1(x) ;
        }
        for(i =0 ; i<n ;i++)
        {
            if(i == n-1)
                printf("%d\n",hash[i]) ;
            else printf("%d ",hash[i]) ;
        }
    }

    return 0 ;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章