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
解题思路:
该题就是PAT 1078的改版,多要求了一个查找时间
查找思路和插入思路一致,使用二次平方探测法(从0开始) 如果查找的位置为目标值或者不存在数字,则表示找到(没找到),保存查找时间退出循环,然后开始查找下一个数字
这里有一个问题一直没想明白,为什么查找的时候还要多加1???是不是题目出错了???
#include <iostream>
#include <algorithm>
#include <math.h>
using namespace std;
const int MAXS = 100010;
int MSize, N, M;
int AveHashTable[MAXS];
bool isprime(int num) {
if (num <= 1) return false;
for (long long i = 2; i*i <= num; ++i) {
if (num % i == 0) return false;
}
return true;
}
int main() {
fill(AveHashTable, AveHashTable + MAXS, -1);
scanf("%d %d %d", &MSize, &N, &M);
while (!isprime(MSize)) {
MSize++;
}
//insert the key
int number;
for (int i = 0; i < N; ++i) {
scanf("%d", &number);
int cpos = number % MSize;
if (AveHashTable[cpos] == -1) {
AveHashTable[cpos] = number;
}
else { //二次探查法
int newpos,cstep = 1;
while (true) {
newpos = (number + cstep * cstep) % MSize;
if (cstep >= MSize) {
printf("%d cannot be inserted.\n", number);
break;
}
if (AveHashTable[newpos] == -1) {
AveHashTable[newpos] = number;
break;
}
cstep++;
}
}
}
//平均查找时间
double aveTime = 0.0;
int snum;
for (int i = 0; i < M; ++i) {
scanf("%d", &snum);
int sstep = 0,stimes = 0;
while (true) {
int searchPos = (snum + sstep * sstep) % MSize;
if (sstep > MSize) { //为什么要多查找一次???????????
break;
}
//查找一次
stimes++;
if (AveHashTable[searchPos] == snum || AveHashTable[searchPos] == -1) { //不存在数字表示也没有找到
break;
}
sstep++;
}
aveTime += (1.0*stimes);
}
printf("%.1lf\n", aveTime / M);
system("PAUSE");
return 0;
}