1145. Hashing - Average Search Time
The task of this problem is simple: insert a sequence of distinct positive integers into a hash table first. Then try to find another sequence of integer keys from the table and output the average search time (the number of comparisons made to find whether or not the key is in the table). The hash function is defined to be ( 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 3 positive numbers: MSize, N, and M, which are the user-defined table size, the number of input numbers, and the number of keys to be found, respectively. All the three numbers are no more than 1. Then N distinct positive integers are given in the next line, followed by M positive integer keys in the next line. All the numbers in a line are separated by a space and are no more than 1.
Output Specification:
For each test case, in case it is impossible to insert some number, print in a line X cannot be inserted.
where X
is the input number. Finally print in a line the average search time for all the M keys, accurate up to 1 decimal place.
Sample Input:
4 5 4
10 6 4 15 11
11 4 15 2
Sample Output:
15 cannot be inserted.
2.8
#include<iostream> #include<cstdio> #include<math.h> using namespace std; int isPrime(int n){ int sqr = sqrt(1.0*n); if(n == 0 || n == 1) return 0; for(int i = 2; i <= sqr; i++){ if(n % i == 0) return 0; } return 1; } int hashTB[200000]; int main(){ int Msize, N, M; scanf("%d%d%d", &Msize, &N, &M); while(!isPrime(Msize)){ Msize++; } fill(hashTB, hashTB + 200000, -1); for(int i = 0; i < N; i++){ int loc, key; scanf("%d", &key); loc = key % Msize; if(hashTB[loc] < 0){ hashTB[loc] = key; }else{ int tag = 0; int q = 1; while(q <= Msize && hashTB[(loc + q*q) % Msize] >= 0){ q++; } if(hashTB[(loc + q*q)%Msize] < 0){ hashTB[(loc + q*q)%Msize] = key; }else{ printf("%d cannot be inserted.\n", key); } } } int cnt = 0; for(int i = 0; i < M; i++){ int key, loc; scanf("%d", &key); loc = key % Msize; int q = 1; cnt++; if(hashTB[loc] != key && hashTB[loc] >= 0){ while(q <= Msize){ if(hashTB[(loc + q*q) % Msize] != key && hashTB[(loc + q*q) % Msize] >= 0){ cnt++; }else{ cnt++; break; } q++; } } } double ans = 1.0 * cnt / M; printf("%.1lf", ans); cin >> N; }
总结:
1、题意:先将元素用平方探测法插入哈希表,再进行查找元素并计算平均比较次数。
2、平方探测: loc = key mod Tsize, 当有冲突时依次探测 (loc ± di^2) mod Tsize,di从1到Tsize - 1(本题di从1到Tsize,题目要求with positive increments only,则探测时正向探测,每次仅加di^2,不用减)。当依次找遍所有位置仍没有空位时插入失败。
3、查找次数。 1)查找成功的情况:一次就查找成功,或者在平方探测的过程中查找成功,记录比较次数。2)查找失败:在平方探测的过程中找到了一个空位,则说明失败;或者平方探测的di取遍了它的范围,沿途位置都非空但却没有找到key。记录比较次数。