PAT 1078

题目 : Hashing

分值 : 25
难度 : 简单题
思路 : 判断素数然后hash概念
坑点 : hash概念有点忘记了......二次平方探查都记不起来了....

具体代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <iostream>
using namespace std;
bool is_prime(int x)
{
if(x==2)
return true ;
if(x<2)
return false ;
for(int i =2 ; i<= x/2 ; i++)
{
if(x%i == 0 )
return false ;
}
return true ;
}
int data[10008] ;
int main() {
int Msize , N ;
cin>>Msize >> N ;
int flag =0 ;
while (!flag)
{
Msize++;
if(is_prime(Msize)) flag =1 ;
}
//cout <<Msize<<endl ;
for(int i = 0 ; i< N ; i++)
{
int temp ;
cin >>temp ;
int h = temp % Msize;
int hash = h ;
bool find =false ;
for(int j = 0 ; j<=Msize ; j++)
{
hash = (h +j*j)%Msize ;
if( data[hash]==0 )
{
find = true ;
data[hash ]=1 ;
break ;
}
}
if(i)
cout <<" ";
if(!find)
cout <<"-" ;
else
cout <<hash ;
}
cout <<endl ;

}