1078 Hashing (25分) 哈希表 教訓

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 (≤10​4​​) 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 -

這題就是模擬哈希表,發生衝突時,採用二次方正向增長解決衝突。

Quadratic probing (with positive increments only) is used to solve the collisions.

英文不好,是硬傷。

第三、四測試點bug了一小時,最後發現是我素數表有問題!

for(i=2;i<100;i++){
        for(j=2;j*i<r;j++){
            prime[i*j]=false;
        }
    }

外層的i我開到20,結果一直報錯!

經過測試,開到80就可以了

#include<iostream>
#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;
const int r=10111;
bool prime[r]={true};
int d[r],index[r],h[r],n,m;
void init(){
	int i,j;
	fill(prime,prime+r,true);
	for(i=2;i<30;i++){
		for(j=2;j*i<r;j++){
			prime[i*j]=false;
		}
	}
	prime[1]=false;
//	for(i=1;i<r;i++){
//		if(prime[i])
//		cout<<i<<" ";
//	}
}
void deal(){
	int i,j,t;
	for(i=0;i<m;i++){
		t=d[i]%n;
		if(h[t]==0){
			h[t]=d[i];
			index[i]=t;
		}
		else{
			int step=1;
            while(h[(d[i]+step*step)%n]!=0){
            	step++;
            	if(step>=n){
            		break;
				}
			}
			if(step>=n){
				index[i]=-1;
			}
			else{
				index[i]=(d[i]+step*step)%n;
				h[(d[i]+step*step)%n]=d[i];
			}
		}
	}
}
int main(){
	int i,j,t;
	fill(index,index+r,-1);
	fill(h,h+r,0);
	init();
	cin>>n>>m;
	for(i=0;i<m;i++)
	cin>>d[i];
	if(prime[n]==false){
		while(prime[n]!=true){
			n++;
		}
	}
	deal();
	for(i=0;i<m;i++){
		if(index[i]!=-1){
			cout<<index[i];
		}
		else{
			cout<<"-";
		}
		if(i<m-1)
		cout<<" ";
	}
	cout<<endl;
	return 0;
}

總結:

1.

Quadratic probing(二次探查法)

Quadratic probing (with positive increments only)
二次探測(正方向)

2.素數表外層開到80!

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章