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

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

Time Limit: 1000MS Memory Limit: 65536KB

Submit Statistic

Problem Description

根据给定的一系列整数关键字和素数p,用除留余数法定义hash函数H(Key)=Key%p,将关键字映射到长度为p的哈希表中,用线性探测法解决冲突。重复关键字放在hash表中的同一位置。

Input

连续输入多组数据,每组输入数据第一行为两个正整数N(N <= 1000)和p(p >= N的最小素数),N是关键字总数,p是hash表长度,第2行给出N个正整数关键字,数字间以空格间隔。

Output

输出每个关键字在hash表中的位置,以空格间隔。注意最后一个数字后面不要有空格。

Example 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

Example Output

1 1 1 1 1
4 0 1 3
4 0 1 2
4 0 1 2 0
#include <iostream>
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 1501;
int a[maxn];
int cnt[maxn];
using namespace std;

int main()
{
   int n, p;
   while(~scanf("%d%d", &n, &p))
   {
       memset(a, -1, sizeof(a));
       memset(cnt, -1, sizeof(cnt));

       for(int i = 1; i<= n; i++)
       {
           int x;
           scanf("%d", &x);
           int hashkey = x%p;
           while(true)
           {
               if(a[hashkey] == -1 || a[hashkey] == x)
               {
                   a[hashkey] = x;
                   cnt[i] = hashkey;
                   break;
               }
               else if(a[hashkey] != -1&&a[hashkey] != x)
               {
                   hashkey = (hashkey+1)%p;
               }
           }

       }
       for(int i = 1; i < n ;i++)
        printf("%d ",cnt[i]);
       printf("%d\n",cnt[n]);

   }
    return 0;
}
#include<stdio.h> #include<string.h> #define maxn 100005 int hash[maxn]; int main() { int n, m, i, j, flag,x; while(~scanf("%d%d", &n, &m)) { memset(hash, -1, sizeof(hash)); for( i = 1; i <= n; i++) { scanf("%d", &x); int id = x % m; if(hash[id] == -1)//原先哈希表里函数对映的空没有存 { printf("%d", id); hash[id] = x; } else//哈希表里对应的存过 分为两种情况1.就是原本的数2.通过线性探测存的数 { for( j = 0; j < m; j++)//对映第一种情况 { flag = 0; if( hash[j] == x) { printf("%d", j);flag = 1;break; } } if(!flag)//对映第二种情况 { while(hash[id % m] != -1) id++;//如果函数里存在数既产生了冲突,则往后一位一位的找 hash[id % m] = x; printf("%d", id%m); } } if( i == n) printf("\n"); else printf(" "); } } } 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值