PAT1078 Hashing (25)(hash:二次探测法)

题意:

给出散列表长和要插入的元素,将这些元素按照读入的顺序插入散列表中,其中散列函数为h(key) = key % TSize,解决冲突采用只向正向增加的二次方探查法。如果题中给出的TSize不是素数,就取第一个比TSize大的素数作为TSize

思路:

这题就是考察一个hash中的处理冲突中的平方探测法,一堆坑:

  1. 平方探测法属于开放定址法中的一种,数学递推公式为Hi=(H(key)+di)%m,其中di=1^2,-1^2...,这题只要求正向
  2. 题目中素数会有1的特例,我是卡在这一步,以后写有关素数的地方要注意一下
#include<iostream>
#include<vector>
#include<cstdio>
#include<string>
#include<map>
#include<cmath>
#include<queue>
#include<functional>
#include<algorithm>
#define inf 0x3f3f3f3f
using namespace std;
const int maxn = 15000;
bool has[maxn];

int main() {
	int Tsize, n,key;
	scanf("%d%d", &Tsize, &n);
	int pos;
	for (pos = Tsize; pos < maxn; pos++) {
		bool flag = true;
		for (int i = 2; i*i <= pos; i++) {
			if (pos%i == 0) {
				flag = false;
				break;
			}
		}
		if (flag)
			break;
	}
	if (pos == 1)
		pos = 2;
	for (int i = 0; i < n; i++) {
		scanf("%d", &key);
		int index = key%pos;
		if (!has[index]) {
			has[index] = true;
			if (i != 0) printf(" ");
			printf("%d", index);
		} else {
			bool flag = true;
			for (int step = 1; step < pos / 2; step++) {
				int t = (index + step*step) % pos;
				if (!has[t]) {
					flag = false;
					has[t] = true;
					if (i != 0) printf(" ");
					printf("%d", t);
					break;
				}
			}
			if (flag) {
				if (i != 0) printf(" ");
				printf("-");
			}
		}
	}
	printf("\n");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/seasonjoe/article/details/80639174