标签:
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 15Sample Output:
0 1 4 -
思路:本文利用了哈希探测法,尤其是二次探测法,一定要记住。另外注意利用二次探测法的边界条件,因为题中给你了只采取递增的形式。
1 #include <iostream> 2 #include <cstdio> 3 #include <cmath> 4 using namespace std; 5 #define MAX 10010 6 int data[MAX]; 7 int ans[MAX]; 8 bool flag[MAX]={false}; 9 bool Judge(int num) 10 { 11 if(num<=1) 12 return false; 13 int sqr=(int)sqrt(1.0*num); 14 for(int i=2;i<=sqr;i++) 15 { 16 if(num%i==0) 17 return false; 18 } 19 return true; 20 } 21 int main(int argc, char *argv[]) 22 { 23 int Msize,N; 24 scanf("%d%d",&Msize,&N); 25 for(int i=0;i<N;i++) 26 { 27 scanf("%d",&data[i]); 28 } 29 if(!Judge(Msize)) 30 { 31 while(++Msize) 32 { 33 if(Judge(Msize)) 34 break; 35 } 36 } 37 //进行映射 38 for(int i=0;i<N;i++) 39 { 40 int index=data[i]%Msize; 41 if(flag[index]) 42 { 43 //进行二次同余 44 bool tem=false; 45 int step=1; 46 do 47 { 48 int a=(data[i]+step*step)%Msize; 49 if(!flag[a]) 50 { 51 tem=true; 52 ans[i]=a; 53 flag[a]=true; 54 break; 55 } 56 step++; 57 }while(step<Msize); 58 if(!tem) 59 ans[i]=-1; 60 } 61 else 62 { 63 ans[i]=index; 64 flag[index]=true; 65 } 66 } 67 for(int i=0;i<N;i++) 68 { 69 if(ans[i]==-1) 70 { 71 if(i!=N-1) 72 printf("- "); 73 else 74 printf("-\n"); 75 } 76 else if(i!=N-1) 77 printf("%d ",ans[i]); 78 else 79 printf("%d\n",ans[i]); 80 } 81 82 return 0; 83 }
标签:
原文地址:http://www.cnblogs.com/GoFly/p/4296864.html