1078 Hashing (25 分)

Hashing
其中平方探测的k通常小于等于m/2

版本1

//1.判断给定的table size是否为素数,不是的话寻找大于该数最小的素数作为替代
//2.平方探测
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e5+5;
int H[maxn]={0};
bool isPrime(int x){
	if(x<=1) return false;
	int sqr = sqrt(x);
	for(int i=2;i<=sqr;i++){
		if(x%i==0) return false;
	}
	return true;
}
int main(){
	int m,n,x;
	cin>>m>>n;
	while(isPrime(m)==false) m++;
	while(n--){
		cin>>x;
		bool flag = false;
		for(int k=0;k<m;k++){
			int now = (x+k*k)%m;
			if(H[now] == 0){
				cout<<now;
				H[now]=1;
				flag=true;
				break;
			}
		}
		if(flag==false) cout<<"-";
		if(n) cout<<" ";
		else cout<<endl;
	}
	return 0;
} 

版本2

#include<bits/stdc++.h>
using namespace std;
bool isPrime(int x){
	if(x <= 1) return false;
	if(x == 2) return true;
	int sqr = sqrt(x);
	for(int i = 2; i <= sqr; i++){ //不要从0开始 
		if(x % i == 0) return false;
	}
	return true;
}
const int maxn = 1e4+5;
bool st[maxn]={false};
int main(){
	int M, N, x;
	cin >> M >>N;
	while(!isPrime(M)) M++;
	for(int i = 0; i < N; i++){
		cin >> x;
		int j;
		if(i) cout<<" ";
		for(j = 0; j < N; j++){
			if(!st[(x + j*j)%M]){
				st[(x + j*j)%M] = true;
				
				cout<<(x + j*j)%M;
				break; 
			}
		}
		if(j == N) cout<<"-";
	} 
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值