Hash的二次探测,当hash的长度为n;插入val,当Hash[val]不为0时,选择新地址newval = val +(-) 1*1,val+(-)2*2,val+(-)(n-1)*(n-1);

 

  具体例题见:PAT1078

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;

int Hash[100000+10];

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

int main()
{
    int tsize,n;
    scanf("%d%d",&tsize,&n);
    while(!isPrime(tsize)) ++tsize;
    bool bFirst = true;
    for(int i=0;i<n;++i)
    {
        int a;
        scanf("%d",&a);
        if(bFirst) bFirst = !bFirst;
        else printf(" ");

        int di;
        for(di=0;di<tsize;++di)
        {
            int add = (a+(di*di))%tsize;
            if(Hash[add]==0)
            {
                printf("%d",add);
                Hash[add] = 1;
                break;
            }
        }
        if(di >= tsize) printf("-");
    }
    printf("\n");
    return 0;
}
View Code

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-02-23
  • 2021-07-21
  • 2021-09-22
  • 2022-12-23
  • 2021-04-06
猜你喜欢
  • 2022-01-05
  • 2022-02-12
  • 2023-01-04
  • 2022-02-05
  • 2021-12-19
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案