【二次方探查法+素数判断】PAT A1078 Hashing

疑问

暂无

代码

#include "bits/stdc++.h"

using namespace std;

const int maxn = 1e4+100;

int msize;

int n;

bool h[maxn] = {0};

bool isPrime(int m){
	//特判1 
	if(m <= 1){
		return false;
	}
	
	//大于等于2,小于等于根号 
	int sqr = (int) sqrt(1.0 * m);
	for(int i=2;i<=sqr;i++){
		if(m % i == 0){
			return false;
		}
	}
	
	return true;
} 

int main(){ 
	scanf("%d %d",&msize,&n);
	
	//求大于等于msize的最小质数 
	for(int i=0;;i++){
		if(isPrime(msize+i)){
			msize = msize + i;
			break;
		}
	}
	
	long long m;
	
	for(int i=0;i<n;i++){
		scanf("%lld",&m);
		int mod;

		int step = 0;	//记录的是步数 
		for(;step < msize;step++){
			mod = (int)((m + (step * step)) % msize);
			if(!h[mod]){
				h[mod] = true;
				printf("%d%c",mod,i!=n-1?' ':NULL); 	
				break;			
			}
		}
		
		if(step == msize){
			printf("-%c",i!=n-1?' ':NULL);
		}
	} 
	return 0;
} 

反思

  1. 题目没看懂,不知道Quadratic probing (with positive increments only) is used to solve the collisions是什么意思,所以测试点3一直没有过:
    在这里插入图片描述在这里插入图片描述在这里插入图片描述

Quadratic probing 是指二次方探查法,即当 H ( a ) H(a) H(a)发生冲突时,让 a a a按照 a + 1 2 , a − 1 2 , a + 2 2 , a − 2 2 , a + 3 2 , a − 3 2 a+1^2,a-1^2,a+2^2,a-2^2,a+3^2,a-3^2 a+12,a12,a+22,a22,a+32,a32…的顺序调整a的值。本题中已经说明只要往正向解决冲突,因此需要按照 a + 1 2 , a + 2 2 , a + 3 2 , . . . a+1^2,a+2^2,a+3^2,... a+12,a+22,a+32,...的顺序调整a的值。

证明如果 s t e p step step 0 0 0 ~ T S i z e − 1 TSize-1 TSize1进行枚举却仍然无法找到位置,那么对 s t e p step step大于等于 T S i z e TSize TSize来说也不可能找到位置(即证明循环节时 T S i z e TSize TSize

在这里插入图片描述

  1. 再次重复:二次方探查法只需要探查到TSize-1就好了。

二刷代码

//宇宙难题,二次勘探法
#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std;
const int maxn = 1e4+100;

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

bool vis[maxn]={0};//初始化为false 

int main(){
	int msize;
	int n;
	scanf("%d %d",&msize,&n);
	while(!isPrime(msize)){
		msize++;
	}
	//printf("%d",msize);
	for(int i=0;i<n;i++){
		int cur;
		scanf("%d",&cur);
		//下面进行二次探测法
		int step=0;
		for(;step<msize;step++){
			if(vis[(cur+step*step)%msize]==false){
				vis[(cur+step*step)%msize]=true;
				break;
			}
		}
		if(step<msize){
			printf("%d",(cur+step*step)%msize);
		}else{
			printf("-");
		}
		
		if(i!=n-1){
			printf(" ");
		} 
	} 
	
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值