1078 Hashing (25分)

题目

The task of this problem is simple: insert a sequence of distinct positive integers into a hash table, and output the positions of the input numbers. The hash function is defined to be H(key)H(key)H(key)=keykeykey%TSizeTSizeTSize where TSizeTSizeTSize is the maximum size of the hash table. Quadratic probing (with positive increments only) is used to solve the collisions.

Note that the table size is better to be prime. If the maximum size given by the user is not prime, you must re-define the table size to be the smallest prime number which is larger than the size given by the user.

Input Specification:

Each input file contains one test case. For each case, the first line contains two positive numbers: MSize(104)MSize(\le10^4)MSize(≤104) and N(MSize)N(\le MSize)N(≤MSize) which are the user-defined table size and the number of input numbers, respectively. Then NNN distinct positive integers are given in the next line. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print the corresponding positions (index starts from 0) of the input numbers in one line. All the numbers in a line are separated by a space, and there must be no extra space at the end of the line. In case it is impossible to insert the number, print “-” instead.

Sample Input:

4 4
10 6 4 15

Sample Output:

0 1 4 -

题目大意

模拟哈希表开放定址法解决冲突的问题,有位置输出位置,没有位置输出-1。
二次探测:
h(i)=(h(key)+i×i)mod(M),0iM1h(i)=(h(key)+i\times i)mod(M),0\le i\le M-1h(i)=(h(key)+i×i)mod(M),0≤i≤M−1,(其中,h是哈希寻址函数,key是要存储的值,M是哈希表的大小,一般使用素数可以达到一个较高的效率)

思路:

找到合适的素数,再按照二次探测的写法写;注意的一个地方就是当输入M为1时,1不是素数,需要将1转换成2.

代码

#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;

const int MAXN = 10010;

int getPrime(int n){
    for(int i=n; ; i++){
        bool flag = true;
        for(int j=2; j<=sqrt(i); j++){
            if(i%j == 0){
                flag = false;
                break;
            }
        }
        if(flag)
            return i;
    }
}

int main(){
    int m, n;
    int a[MAXN], p[MAXN], ans[MAXN];
    scanf("%d %d", &m, &n);
    if(m == 1)
        m = 2;
    else
        m = getPrime(m);
    fill(a, a+m, -1);
    for(int i=0; i<n; i++){
        int d, t;
        scanf("%d", &d);
        fill(p, p+m, 0);
        t = d % m;
        for(int k=0, temp; ;k++){
            temp = (t+k*k) % m;
            if(p[temp] == 1)
                break;
            if(a[temp] == -1){
                t = temp;
                break;
            }
            p[temp] = 1;
        }
        if(a[t] == -1){
            a[t] = d;
            ans[i] = t;
        }
        else
            ans[i] = -1;
    }
    for(int i=0; i<n; i++){
        if(i)
            printf(" ");
        if(ans[i] > -1)
            printf("%d", ans[i]);
        else
            printf("-");
    }
    return 0;
}
上一篇:1078 Hashing (25)


下一篇:PTA(Advanced Level)1078.Hashing