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 \% TSizeH(key)=key%TSize where TSizeTSize 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: MSizeMSize (\le 10^4≤10?4??) and NN (\le MSize≤MSize) which are the user-defined table size and the number of input numbers, respectively. Then NN 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 15
Sample Output:
0 1 4 -
解答
这题主要是生成素数的算法,通过Make_Prime函数实现,还有就是平方探测开放寻址时,当用于探测的量j(每次拿j * j探测)等于Hash表的Size的时候,待插入的数还没有插入的话,就可以判断出待插入的数将永远无法插入。
// // main.c // Hashing // // Created by 余南龙 on 2016/12/8. // Copyright ? 2016年 余南龙. All rights reserved. // #include <stdio.h> #include <string.h> #define MAX 10008 int prime[MAX], hash[MAX]; void Make_Prime(){ int i, j; prime[0] = prime[1] = 1; for(i = 2; i < MAX; i++){ if(0 == prime[i]){ for (j = i * i; j < MAX; j += i) { prime[j] = 1; } } } } void Hashing(){ int M, N, i, j, val; memset(hash, -1, MAX * sizeof(int)); scanf("%d%d", &M, &N); while (0 != prime[M]) { M++; } for (i = 0; i < N; i++) { scanf("%d", &val); for (j = 0; j < M; j++) { if(-1 == hash[(val % M + j * j) % M]){ hash[(val % M + j * j) % M] = val; if(0 == i){ printf("%d", (val % M + j * j) % M); } else{ printf(" %d", (val % M + j * j) % M); } break; } } if(j == M){ if(0 == i){ printf("-"); } else{ printf(" -"); } } } } int main() { Make_Prime(); Hashing(); }