5.4 素数1078 Hashing (25 分)(*题意理解)

60 篇文章 0 订阅
50 篇文章 0 订阅

Quadratic probing (with positive increments only) is used to solve the collisions.
(哈希表)用二次方探测法来解决矛盾(此题只需要考虑正向);

二次方探测法证明,只需要算到步长为止,如果超过步长还是冲突则之后也是一样
摘自《算法笔记》
在这里插入图片描述

主要是题目没读懂,读懂了这道题难度一般

#include <cstdio>
#include <cmath>
bool isPrime(int n)
{
    if(n<=1)return false;
    for(int i = 2;i<=sqrt(n);i++)
    {
        if(n%i==0)return false;
    }
    return true;
}



int main()
{
    int m,n;
    int num[10010];
    bool H[10010]={0};
    scanf("%d%d",&m,&n);
    int tm = m;
    while(isPrime(tm)==false)
    {
        tm++;
    }
    for(int i = 0;i<n;i++)
    {
        scanf("%d",&num[i]);
        int temp = num[i] %tm;
        if(H[temp] == false)
        {
            H[temp] = true;
            printf("%d",temp);
        }
        else if(H[temp] == true)
        {
            int temp1;
            int flag = 0;
            for(int j = 1;j<=tm;j++)
            {
                temp1 = (num[i] + j*j)%tm;
                if(H[temp1] == false)
                {
                    H[temp1] = true;
                    printf("%d",temp1);
                    flag = 1;
                    break;
                }

            }
            if(flag == 0)
                printf("-");
//            temp++;
        }
        if(i<n-1)
            printf(" ");

    }
//    printf("%d",n);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值