09-散列1. 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 (<=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 410 6 4 15Sample Output:
0 1 4 -
注意边界测试!
1 #include2 #include 3 #include 4 #include 5 #include 6 #include 7 using namespace std; 8 bool h[10005]; 9 int GetNextPrime(int num){10 int i,j;11 if(num==1){ //注意边界12 return 2;13 }14 if(num==2){ //注意边界15 return 2;16 }17 for(i=num;;i++){18 if(i%2==0){19 continue;20 }21 for(j=3;j*j<=i;j+=2){22 if(i%j==0){23 break;24 }25 }26 if(j*j>i){27 return i;28 }29 }30 }31 int main(){32 //freopen("D:\\INPUT.txt","r",stdin);33 int msize,n;34 scanf("%d %d",&msize,&n);35 int i,num,j;36 memset(h,false,sizeof(h));37 msize=GetNextPrime(msize);38 queue q;39 for(i=0;i msize/2){57 q.push(-1);58 }59 }60 }61 int now;62 if(!q.empty()){63 now=q.front();64 q.pop();65 if(now==-1){66 printf("-");67 }68 else{69 printf("%d",now);70 }71 }72 while(!q.empty()){73 now=q.front();74 q.pop();75 if(now==-1){76 printf(" -");77 }78 else{79 printf(" %d",now);80 }81 }82 printf("\n");83 return 0;84 }