PAT Advanced 1145. Hashing - Average Search Time (25)

问题描述:

1145. Hashing - Average Search Time (25)

时间限制
200 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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 two 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. 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


这题需要注意的是:在查找失败时,比较次数应该是Tsize+1而不是Tsize;

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
#include<bits/stdc++.h>
using namespace std;
int main()
{
  	ios::sync_with_stdio(false);
//	freopen("data.txt","r",stdin);
	int n,m,k,x;
	cin>>n>>m>>k;
	vector<bool> v(n+100,true);
	int i;
	for(i=2;i<v.size();i++)
	{
		if(v[i])
		{
			if(i>=n)
			break;
			for(int j=2;j*i<v.size();j++)
			{
				v[i*j]=false;
			}
		}
	}

	vector<int> v0(i,0);
	for(;m--;)
	{
		cin>>x;
		int j=0;
		for(;j<i;j++)
		{
			int xv=(x+j*j)%i;
			if(!v0[xv])
			{
				v0[xv]=x;
				break;
			}
		}
		if(j==i)
		printf("%d cannot be inserted.\n",x);
	}
	double s=0.0;
	m=k;
	for(;m--;)
	{
		cin>>x;
		int xv=x%i,j=0;
		for(;j<i;j++)
		{
			xv=(x+j*j)%i;
			if(v0[xv]==x||!v0[xv])
			break;
		}
		s=s+j+1;
	}
	s=s/k;
	printf("%.1f",s);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/baidu_37550206/article/details/79705252