PTA甲级考试真题练习78——1078 Hashing

题目

PTA甲级考试真题练习78——1078 Hashing_第1张图片

思路

用二次探测法求hash散列

坑点

栽在了素数判断上:1不是素数,当输入n=1的时候直接返回false,否则会返回true。

代码

#include 
using namespace std;
#define nmax 10050
#define inf 999999
int hashTable[nmax];
int nsize, n;

bool JudgePrime(int  n) {
    if(n<=1)
        return false;
	int sqrtn = sqrt((double)n);
	for (int i = 2; i <= sqrtn; ++i) {
		if (n % i == 0)
			return false;
	}
	return true;
}

bool dealInsert(int n, int& _index) {
	int Mul = 1;
	int tmp = n;
	while (Mul <= nsize/2) {
		if (hashTable[tmp] == 0) {
			hashTable[tmp]++;
			_index = tmp;
			return true;
		}
		tmp = (int)(n + pow(Mul++, 2)) % nsize;
	}
	return false;
}

int main()
{
	cin >> nsize >> n;
	while (!JudgePrime(nsize))
		nsize++;
	memset(hashTable, 0, sizeof(hashTable));
	for (int i = 0; i < n; ++i) {
		int tmp,_index = -1;
		cin >> tmp;
		if (i == 0) {
			if (dealInsert(tmp % nsize, _index))
				cout << _index;
			else
				cout << "-";
		}
		else {
			if (dealInsert(tmp % nsize, _index))
				cout <<" "<< _index;
			else
				cout <<" -";
		}
	}
	return 0;
}

你可能感兴趣的:(PAT甲级考试真题练习)