E - Find the experimental data structures seven: the linear hash table

Description

According to a given set of keywords and an integer prime number p, defined by I stay except hash function H (Key) = Key% p, keyword mapping to a hash table of length p, the detection method of conflict resolution linear . Duplicate keywords in the same location in the hash table.
Input

Enter multiple sets of data, each set of input data a first two acts of positive integers N (N <= 1500) and p (p> = minimum prime number N), N is the total number of keywords, p is the length of the hash table, the second line gives N positive integers between keywords, the digital interval spaces.
Output

Output position each keyword hash table, a space interval. Note that the last digit behind with no spaces.
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
Output

1 1 1 1 1
4 0 1 3
4 0 1 2
4 0 1 2 0

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
    int hax[1600],v[1600],n,m,i,len,j,k;
    while(~scanf("%d %d",&n,&m))
    {
        len = 0;
        memset(hax,-1,sizeof(hax));
        for(i=0;i<n;i++)
        {
            scanf("%d",&k);
            int id = k% m;
            if(hax[id] == -1)
            {
                hax[id] = k;
                v[len++] = id;
            }
             else
             {
                 for(j=0;j<m;j++)
                 {
                     if(hax[(k+j)%m] == k)//重复关键字放在hash表中的同一位置。
                     {
                         v[len++] = (k+j)%m;
                         break;
                     }
                     else
                     {
                         if(hax[(k+j)%m] == -1)
                         {
                             hax[(k+j)%m] = k;
                             v[len++] = (k+j)%m;
                             break;
                         }
                     }
                 }
             }
        }
        for(i=0;i<len;i++)
        {
            if(i == len-1)
                printf("%d\n",v[i]);
            else
                printf("%d ",v[i]);
        }

    }
    return 0;
}

Published 176 original articles · won praise 7 · views 30000 +

Guess you like

Origin blog.csdn.net/Fusheng_Yizhao/article/details/104924892