SDUT 3377 数据结构实验之查找五:平方之哈希表

数据结构实验之查找五:平方之哈希表

Time Limit: 400 ms Memory Limit: 65536 KiB

Submit Statistic

Problem Description

给定的一组无重复数据的正整数,根据给定的哈希函数建立其对应hash表,哈希函数是H(Key)=Key%P,P是哈希表表长,P是素数,处理冲突的方法采用平方探测方法,增量di=±i^2,i=1,2,3,...,m-1

Input

输入包含多组测试数据,到 EOF 结束。

每组数据的第1行给出两个正整数N(N <= 500)和P(P >= 2N的最小素数),N是要插入到哈希表的元素个数,P是哈希表表长;第2行给出N个无重复元素的正整数,数据之间用空格间隔。

Output

按输入数据的顺序输出各数在哈希表中的存储位置 (hash表下标从0开始),数据之间以空格间隔,以平方探测方法处理冲突。

Sample Input

4 11
10 6 4 15
9 11
47 7 29 11 9 84 54 20 30

Sample Output

10 6 4 5
3 7 8 0 9 6 10 2 1

Hint

Source

xam

#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <iostream>
#include <list>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <vector>
#define inf 0x3f3f3f3f
using namespace std;
int a[2000];
int Hash[2000];
int main() {
    int n, p;
    while (cin >> n >> p) {
        for (int i = 0; i < n; i++) {
            cin >> a[i];
        }
        memset(Hash, inf, sizeof(Hash));
        for (int i = 0; i < n; i++) {
            int key = a[i] % p;
            if (Hash[key] == inf) {  // 如果这个地方没有存放数据,可以存放
                Hash[key] = a[i];  // Hash 表存value
                a[i] = key;        //里面更改成存放 key
            } else {
                // 正反向寻找
                for (int j = 1;; j++) {
                    int temp = j * j;
                    if (Hash[(key + temp) % p] == inf) {
                        Hash[(key + temp) % p] = a[i];
                        a[i] = (key + temp) % p;
                        break;
                    } else if (Hash[(key - temp) % p] == inf) {
                        Hash[(key - temp) % p] = a[i];
                        a[i] = (key - temp) % p;
                        break;
                    }
                }
            }
        }

        for (int i = 0; i < n; i++) {
            printf(i == n - 1 ? "%d\n" : "%d ", a[i]);
        }
    }
    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值