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 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 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 10
4
. 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 10
5
.
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
分析:
哈希表的应用,将n个元素插入到哈希表中,然后查找m个关键词,输出平均查找次数(保留一位小数)。注意这里的p的范围为q<=MSize。
#include<iostream>
#include<vector>
#include<algorithm>
#include<cmath>
using namespace std;
int MSize, N, M;
vector<int>hashtable;
bool is_prime(int n) {
int k = sqrt(n);
if (n == 2)return true;
for (int i = 2; i <= k; i++) {
if (n%i == 0)return false;
}
return true;
}
void insert(int num) {
int s = num % MSize;
for (int i = 0; i <= MSize; i++) {
int k = (s+ i * i) % MSize;
if (hashtable[k] == -1) {
hashtable[k] = num; return;
}
}
cout << num << " cannot be inserted." << endl;
}
int find(int num) {
int s = num % MSize, i;
for (i = 0; i <= MSize; i++) {
int k = (s + i * i) % MSize;
if (hashtable[k] == num||hashtable[k]==-1)return i + 1;
}
return MSize + 1;
}
int main() {
int num, sum = 0;
double avgNum;
cin >> MSize >> N >> M;
while (!is_prime(MSize)) {
MSize++;
}
hashtable.resize(MSize, -1);
for (int i = 1; i <= N; i++) {
scanf_s("%d", &num);
insert(num);
}
for (int i = 1; i <= M; i++) {
scanf_s("%d", &num);
sum += find(num);
}
avgNum = sum * 1.0 / M + 0.05;
printf("%.1f", avgNum);
return 0;
}
欢迎评论!!!