1078 Hashing

题意:给出表长和待插入的元素,求每个元素的插入位置,散列函数为H(key)=key%TSize,解决冲突利用平方探测法(只考虑正向偏移)。

思路:同1145 Hashing - Average Search Time

代码:

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

bool isPrime(int n)
{
    if(n<=1) return false;
    int sqr=(int)sqrt(n);
    for(int i=2;i<=sqr;i++)
        if(n%i==0) return false;
    return true;
}

int main()
{
    int MSize,n,key;
    scanf("%d%d",&MSize,&n);
    while(!isPrime(MSize)) 
        MSize++;
    bool exist[10005]={false};//exist[i]为true表示位置i已经被占据了
    int data[10005];
    unordered_map<int,int> pos;//pos[val]存放val的位置
    for(int i=0;i<n;i++){
        scanf("%d",&key);
        data[i]=key;
        int d=0;
        for(;d<MSize;d++){
            int p=(key+d*d)%MSize;
            if(exist[p]==false){
                exist[p]=true;
                pos[key]=p;
                break;
            }
        }
        if(d==MSize) pos[key]=-1;
    }
    for(int i=0;i<n;i++){
        if(pos[data[i]]==-1) printf("-");
        else printf("%d",pos[data[i]]);
        if(i<n-1) printf(" ");
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/kkmjy/p/9550673.html