A1145 Hashing - Average Search Time (25 point(s))

散列-再散列 查找失败平均长度

1. 原文

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 Xis 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:

1
2
3
4 5 4
10 6 4 15 11
11 4 15 2

Sample output:

1
2
15 cannot be inserted.
2.8

2. 解析

散列函数 hash(x)=(x+i*i)%msize;

插入表索引为0-msize-1

查找表0-msize ,最后一个都不找到才算查找失败

插入成功 hash[h]=a

查找成功 hash[h]==a||hash[h]==0

3. AC代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include<cstdio>
#include<cmath>
#include<map>
using namespace std;
map<int,int> hashtable;
bool isPrime(int x){
int sqr=sqrt(1.0*x);
for (int i = 2; i <= sqr; ++i)
{
if (x%i==0)
{
return false;
}
}
return true;
}
int main()
{
int msize,n,m;
scanf("%d%d%d",&msize,&n,&m);
while(!isPrime(msize)){
msize++;
}
int a;
for (int i = 0; i < n; ++i)
{
int flag=0;
scanf("%d",&a);
for (int j = 0; j < msize; ++j)
{
int h=(a+j*j)%msize;
if (hashtable[h]==0)
{
flag=1;
hashtable[h]=a;
break;
}
}
if (flag==0)
{
printf("%d cannot be inserted.\n",a);
}
}
int ans=0;
for (int i = 0; i < m; ++i)
{
scanf("%d",&a);
for (int j = 0; j <= msize; ++j)
{
ans++;
int h=(a+j*j)%msize;
if (hashtable[h]==a||hashtable[h]==0)
{
break;
}
}
}
printf("%.1f\n", 1.0*ans/m);
return 0;
}

查找失败为hashtable[h]==a||hashtable[h]==0

本文结束  感谢您的阅读
  • 本文作者: Wang Ting
  • 本文链接: /zh-CN/2019/09/02/A1145/
  • 发布时间: 2019-09-02 14:58
  • 更新时间: 2021-10-29 14:10
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!