1078 Hashing (25分)

The task of this problem is simple: insert a sequence of distinct positive integers into a hash table, and output the positions of the input numbers. The hash function is defined to be H(key)=key%TSize where TSize is the maximum size of the hash table. Quadratic probing (with positive increments only) is used to solve the collisions.

Note that the table size is better to be prime. If the maximum size given by the user is not prime, you must re-define the table size to be the smallest prime number which is larger than the size given by the user.

Input Specification:

Each input file contains one test case. For each case, the first line contains two positive numbers: MSize (≤104) and N (≤MSize) which are the user-defined table size and the number of input numbers, respectively. Then N distinct positive integers are given in the next line. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print the corresponding positions (index starts from 0) of the input numbers in one line. All the numbers in a line are separated by a space, and there must be no extra space at the end of the line. In case it is impossible to insert the number, print "-" instead.

Sample Input:

4 4
10 6 4 15

Sample Output:

0 1 4 -

题目描述:把哈希表实现出来。


输入:Msize数组长度,n插入值得个数

输出:插入每个值得位置


解题思路:Quadratic probing (with positive increments only) is used to solve the collisions.

这句话是重点,必须理解,Quadratic二次方,probe探测,collision冲突;遇到冲突使用二次探测存放!

二次探测公式:H(Key) = (Key + i*i) (i=0....n-1)

解这道题,因为哈希表得的长度规定选为素数,所以,当Msize不为素数,需要将大于Msize的最小素数求出,可以用一个数组先将素数表存好,方便查询。然后把二次探测公式实现就行了。


#include<bits/stdc++.h>
using namespace std;
const int maxn = 20005;
vector<int> prime;
int p[maxn];
bool is_prime(int k){
	if(k==0||k==1) return false;
	for(int i=2; i<=sqrt(k); i++){
		if(k%i==0) return false;
	}
	return true;
}
int find_prime(int k){
	for(int i=0; i<prime.size(); i++){
		if(prime[i]>k) return prime[i];
	}
	return 0;
}
int main()
{
	memset(p,-1,sizeof(p));
	prime.push_back(2);
	for(int i=3; i<=maxn; i+=2){
		if(is_prime(i)) prime.push_back(i);
	}
	int n, m;
	long long k;
	scanf("%d %d", &n, &m);
	if(!is_prime(n)) n = find_prime(n);
	
	for(int i=0; i<m; i++){
		scanf("%lld", &k);
		if(i) printf(" ");
		int g = k%n, c=0;
		while(p[g]!=-1&&c<n){
			c++;
			g = (k+c*c)%n;
		}
		if(p[g]!=-1) printf("-");
		else{
			p[g%n] = g%n;
			printf("%d", g%n);
		}
	}
	return 0;
}