PTA 11-散列2 Hashing (25 分)

#include <bits/stdc++.h>
using namespace std;
bool isPrime(int n);
int main()
{
	#ifdef ONLINE_JUDGE
	#else
	freopen("in.txt", "r", stdin);
	#endif
	
	int Max, N; //Max用來存儲哈希表的長度
	scanf("%d%d", &Max, &N);
	while(!isPrime(Max)){
		Max++;
	} 
	
	vector<int> hash(Max, -1);
	int i, j;
	int tmp, flag = 0, pos;
	
	for(i = 0; i < N; i++){
		scanf("%d", &tmp);
			
		for(j = 0; j < Max; j++){
			pos = (tmp + j*j) % Max;
			flag = 0;
			
			if(hash[pos] == -1){
				hash[pos] = 1;
						
				if(i != 0) printf(" ");
				printf("%d", pos);
				flag = 1;
				break;
			} 
		}
		if(flag == 0) printf(" -");
	}
	
	return 0;
}

bool isPrime(int n)
{
	int i;
	if(n <= 1) return false;
	for(i = 2; i <= sqrt(n); i++){
		if(n%i == 0) return false;
	}
	
	return true;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章