1078. 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 4 10 6 4 15Sample Output:
0 1 4 -
题目要求使用正平方探测的方式维护一张表长为素数的哈希表,题目的易错点在于素数的判定。
一定要注意,2是第一个素数。
所谓平方探测,就是从当前位置开始,依次加上1^2 = 1、2^2 = 4、3^2 = 9...直到找到合适的位置或者平方系数大于等于表长M,如果直到平方系数大于等于表长M都没有找到合适位置,则说明插入失败,用-1标记。
插入过程中用一个vector记录输入元素插入的位置,如果插入失败,用-1标记,在输出时碰到-1输出-即可。
代码如下:
#include <iostream> #include <stdio.h> #include <vector> using namespace std; struct HashNode{ bool saved; HashNode(){ saved = false; } }; int M,N; vector<HashNode> hashTable; vector<int> positions; int getKey(int value){ return (value % M); } void hashSave(int value, int index){ int pos = getKey(value); HashNode *node = &hashTable[pos]; if(!node->saved){ node->saved = true; positions[index] = pos; }else{ int factor = 1; while(factor < M){ int tryPos = pos + factor * factor; while(tryPos >= M) tryPos -= M; node = &hashTable[tryPos]; if(!node->saved){ node->saved = true; positions[index] = tryPos; return; }else{ factor++; } } positions[index] = -1; } } int nearestPrime(int n){ if(n <= 2) return 2; if(n % 2 != 0) return n; while(1){ bool isPrime = true; for(int i = n - 1; i > 1; i--){ if(n % i == 0){ isPrime = false; break; } } if(isPrime) break; n++; } return n; } int main() { cin >> M >> N; M = nearestPrime(M); hashTable.resize(N); positions.resize(M); int num; for(int i = 0; i < N; i++){ scanf("%d",&num); hashSave(num,i); } if(num == -1) printf("-"); else printf("%d",positions[0]); for(int i = 1; i < N; i++){ num = positions[i]; if(num == -1) printf(" -"); else printf(" %d",num); } cout << endl; return 0; }