【2019暑期】【PAT甲级】1145 Hashing - Average Search Time (25 分)

本文介绍了一种使用平方探测法实现哈希表的方法,通过寻找下一个可用位置的二次探查来解决哈希冲突。文章详细展示了如何选择合适的哈希表大小(质数),并实现了元素插入和查找的算法流程。通过对多个输入数据进行插入操作,当发生冲突时,利用平方探测法找到空闲槽位。在查找元素时,采用相同策略直至找到目标或确定不存在为止。最后计算平均查找次数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

平方探测法

#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <iostream>
#include <string>
#include <cctype>
#include <vector>
#include <cmath>
#include <map> 
#include <set>
using namespace std;

int size,n,m; 

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

int main(){
	
	cin >> size >> n >> m;
	while(isprime(size)==false){
		size += 1;		
	}
	vector<int> ans(size);
	for(int i=0; i<n; i++){
		int a;
		int flag = 0;
		cin >> a;
		if(ans[a%size]==0){
			ans[a%size] = a;
			flag = 1;
		}
		else {
			for(int j=1; j<=size; j++){
				if(ans[(a+j*j)%size]==0){
					ans[(a+j*j)%size] = a;
					flag = 1;
					break;
				}
			}
		}
		if(flag == 0) cout << a << " cannot be inserted." << endl;
	}
	int time = 0;
	for(int i=0; i<m; i++){
		int a;
		cin >> a;
		for(int j=0; j<=size; j++){
			if(ans[(a+j*j)%size]==a){
				time++;
				break;
			}
			else if(ans[(a+j*j)%size]==0 || j==size){
				time++;
				break;
			}
			time++;
		} 
	}
	printf("%0.1lf",time*1.0/m);
		
	return 0;
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值