1078 Hashing

水题,

主要是Quadratic probing的定义没搞清,fuck!

注意:判断质数的函数小心2和3:

bool isPrime(int x){
	if(x <= 1){
		return false;
	}
	if(x == 2 || x ==3){//fuck!  1059里判断质数的函数写错了! 
		return true;
	}

	int tmp = sqrt(float(x))+1;

	for(int i = 2; i <= tmp; i++){
		if(x%i == 0){
			return false; 
		}
	}

	return true;
}
#include <stdio.h>
#include <string.h>
#include <math.h>
using namespace std;
 

bool isPrime(int x){
	if(x <= 1){
		return false;
	}
	if(x == 2 || x ==3){//fuck!  1059里判断质数的函数写错了! 
		return true;
	}

	int tmp = sqrt(float(x))+1;

	for(int i = 2; i <= tmp; i++){
		if(x%i == 0){
			return false; 
		}
	}

	return true;
}


int msize, n;

int t[10000+10];


int main(){
	freopen("in.txt","r",stdin);

	scanf("%d%d",&msize, &n);	

	while(!isPrime(msize)){
		msize++;
	}

	//tst
	//printf("msize = %d\n",msize);

	memset(t, 0, sizeof(t));
	 

	int key;
	bool flag = true;
	 
	for(int i = 0; i < n; i++){
		
		scanf("%d", &key);
		int hash = key%msize;

		if(t[hash] == 0){
			t[hash] = key;

			if(flag){
				printf("%d",hash);
				flag = false;
			}else{
				printf(" %d", hash);
			}
		}else{
			
			int qua = 1;
			int originalHash = hash;
			 
			while(t[hash] !=  0 && qua < msize){ //二次探测的终止条件是 qua == msize,fuck!
				 
				hash = (originalHash + qua*qua)%msize;//hash += qua*qua;这样写错的!				
				qua++;			
			}

			if(t[hash] ==  0){
				t[hash] = key;
				printf(" %d", hash);
			}else{
				printf(" -");
			}
		}
	
	}



	return 0;
}




你可能感兴趣的:(1078 Hashing)