PAT甲级-质数类型-1078 Hashing解题思路

1078 Hashing (25 分)

在这里插入图片描述

思路

二次探查方法搜索方法乱定导致不能AC,要根据算法设置为哈希表大小

Quadratic probing (with positive increments only) is used to solve the collisions.

二次探测(只有正的增量)用于解决碰撞。

代码

#include<bits/stdc++.h>
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 M,N;
    cin>>M>>N;
    
    while(!isPrime(M))
    {
    
    M+=1;}

    int num;
    int j;
    bool flag[1000005] ={
    
    false};
    for(int i =0;i<N;i++)
    {
    
    
        cin>>num;
        for(j=0;j<10005;j++)  //二次探查方法搜索方法乱定导致不能AC,要根据算法设置为哈希表大小
        {
    
    
            int ans = (num+j*j)%M;
            if(flag[ans]==false)
            {
    
    
                flag[ans] = true;
                cout<<ans;
                break;
            }
            else continue;
        }
        if(j==10005)cout<<"-";
        if(i!=N-1)cout<<" ";
    }
    cout<<endl;
}

猜你喜欢

转载自blog.csdn.net/weixin_43999137/article/details/114643819