SDUT-3379-->数据结构实验之查找七:线性之哈希表

来源:互联网 发布:程序员招聘要求英文 编辑:程序博客网 时间:2024/05/02 02:31

数据结构实验之查找七:线性之哈希表

Time Limit: 1000MSMemory Limit: 65536KB
  

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 521 21 21 21 214 524 15 61 884 524 39 61 155 524 39 61 15 39

Example Output

1 1 1 1 14 0 1 34 0 1 24 0 1 2 0

Hint

Author

xam 
参考代码:
#include <iostream>#include <stdio.h>#include <string.h>using namespace std;int a[1555];int ha[1555];int ans[1555];void Hash(int n,int p){    memset(ha,0,sizeof(ha));    for(int i=0; i<n; i++)    {        int pos = a[i]%p;        if(ha[pos] == 0)        {            ha[pos] = a[i];            ans[i] = pos;        }        else if(ha[pos] == a[i])        {            ans[i] = pos;        }        else if(ha[pos]!=a[i])        {            for(int j=(pos+1)%p; j%p<p; j++)            {                j = j%p;//当到表尾时可以转到表头                if(ha[j] == 0)                {                    ha[j] = a[i];                    ans[i] = j;                    break;                }                else if(ha[j] == a[i])                {                    ans[i] = j;                    break;                }            }        }    }}int main(){    int n,p;    while(scanf("%d%d",&n,&p)!=EOF)    {        for(int i=0;i<n;i++)        {            scanf("%d",&a[i]);        }        Hash(n,p);        for(int i=0;i<n;i++)        {            if(i == n-1)                printf("%d\n",ans[i]);            else                printf("%d ",ans[i]);        }    }    return 0;}


阅读全文
0 0
原创粉丝点击