1145 Hashing - Average Search Time (25 分)
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 104. 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 105.
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
哈希查找嘛 处理方法有一个是二次方探测再散列 。 本来其实只要遍历 0 -- (masize+1)/2 就可以了,后面会出现某种循环。
但是此题是 最普通的方法 是遍历 0 - masize 并且没有找到的话是 比较了 maszie+1 次,最后一次是 比较了一次发现没有元素进行比较了。
数组开辟的话最少开 10007 因为 10000个数 最小切大于的质数是10007;
查找不到 是 分俩种情况 一种是把所有要查的元素查完 还是没找到, 还一种是查到了没有放元素的空值 。
code
#pragma warning(disable:4996)
#include <iostream>
#include <cmath>
#include <cstdio>
#include <cstring>
using namespace std;
int table[10010];
bool isprime(int x) {
if (x < 2) return 0;
for (int i = 2; i <= int(sqrt(x)); ++i) {
if (x%i == 0) return 0;
}
return 1;
}
int dealsize(int x) {
while (!isprime(x)) {
x++;
}
return x;
}
bool insert(int x, int n) {
int p = x % n;
for (int i = 0; i < n; ++i) {
int pp = (p + i * i) % n;
if (table[pp] == -1) {
table[pp] = x;
return 1;
}
}
return 0;
}
int findtime(int x,int n) {
int p = x % n;
int num = 0;
for (int i = 0; i < n; ++i) {
int pp = (p + i * i) % n;
num++;
if (table[pp] == x || table[pp] == -1) {
return num;
}
}
return num+1;
}
int main() {
int msize, n, m, x;
memset(table, -1, sizeof(table));
cin >> msize >> n >> m;
msize = dealsize(msize);
for (int i = 0; i < n; ++i) {
cin >> x;
if (!insert(x,msize)) cout << x << " cannot be inserted." << endl;
}
int time = 0;
for (int i = 0; i < m; ++i) {
cin >> x;
time += findtime(x,msize);
}
printf("%.1f\n", (time*1.0) / m);
system("pause");
return 0;
}