[DS][Hash][PAT][Hashing]

来源:互联网 发布:阿里云api怎么解析 编辑:程序博客网 时间:2024/05/17 05:53

11-散列2 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 TSizeis 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 15

Sample Output:

0 1 4 -


#include <iostream>using namespace std;struct HashTbl {int *Elements;int *Status;int TableSize;};typedef HashTbl *HashTable;int NextPrime(int x);HashTable Create(int TableSize);int Insert(int Key, HashTable H);int main(){int MSize, N, x, i, *Index;HashTable H;cin >> MSize >> N;H = Create(MSize);Index = new int[N];for (int i = 0; i != N; ++i) {cin >> x;Index[i] = Insert(x, H);}for (i = 0; i != N - 1; ++i) {if (Index[i] > -1) {cout << Index[i] << " ";} else {cout << "-" << " ";}}if (Index[i] > -1) {cout << Index[i] << endl;} else {cout << "-" << endl;}delete []H->Elements;delete []H->Status;delete H;}int NextPrime(int x){for (int next = x; ; ++next) {int i;for (i = 2; i * i <= next; ++i) {if (next % i == 0) break;}if (i * i > next) {//cout << next;return next;}}}HashTable Create(int TableSize){HashTable H;H = new HashTbl;H->TableSize = NextPrime(TableSize);H->Elements = new int[H->TableSize];H->Status = new int[H->TableSize];for (int i = 0; i != H->TableSize; ++i) {H->Status[i] = -1;}return H;}int Insert(int Key, HashTable H){int pos, nowPos;//FindnowPos = pos = Key % H->TableSize;for (int i = 1; H->Status[nowPos] != -1; ++i) {if (H->Status[nowPos] == 1) break;H->Status[nowPos] = 1;//collision have processednowPos = pos + i * i;if (nowPos >= H->TableSize) {nowPos -= H->TableSize;}}//Insertif (H->Status[pos] == -1) {H->Elements[pos] = Key;H->Status[pos] = 0;return pos;} else {for (int i = 0; i != H->TableSize; ++i) {if (H->Status[i] == 1) {H->Status[i] = 0;}}return -1;}}








0 0