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.
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.
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.
4 5 4
10 6 4 15 11
11 4 15 2
15 cannot be inserted.
2.8
要做事项如下:
1.用户自定义表不一定是hash表长,需要取最小的大于等于其的素数,可能会超过1e4,为保险起见直接开2e4
2.所谓二次探测是 :
(开放地址发——二次方探测再散列)
其中di = 1,2,4,9,...,(TSize-1)^2
因为题目中的条件限制,所以我们只需要考虑正增量即可。
3.此题其实有误,如果元素不在hash表内查找次数应该是表长,而不是表长+1,为了AC我这里是取表长+1~
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define rg register ll
#define inf 2147483647
#define lb(x) (x&(-x))
/* ll sz[200005],n; */
template <typename T> inline void read(T& x)
{
x=0;char ch=getchar();ll f=1;
while(!isdigit(ch)){if(ch=='-')f=-1;ch=getchar();}
while(isdigit(ch)){x=(x<<3)+(x<<1)+(ch^48);ch=getchar();}x*=f;
}
/* inline ll query(ll x){ll res=0;while(x){res+=sz[x];x-=lb(x);}return res;}
inline void add(ll x,ll val){while(x<=n){sz[x]+=val;x+=lb(x);}}//第x个加上val */
ll Ms,n,m,check,a[20000];
inline bool prime(ll x)
{
if(x==1||x==2)return 1;
for(rg i=2;i*i<=x;i++)
{
if(x%i==0)return 0;
}
return 1;
}
int main()
{
cin>>Ms>>n>>m;
check=Ms;
while(!prime(check))
{
check++;
//cout<<check<<endl;
}
for(rg i=1;i<=n;i++)
{
ll x,flag=0;
cin>>x;
for(rg j=0;j<check;j++)
{
if(!a[(x+j*j)%check])
{
a[(x+j*j)%check]=x,flag=1;
break;
}
}
if(!flag)cout<<x<<" cannot be inserted."<<endl;
}
ll ans=0;
for(rg i=1;i<=m;i++)
{
ll x;
cin>>x;
for(rg j=0;j<=check;j++)
{
ans++;
if(!a[(x+j*j)%check]||a[(x+j*j)%check]==x)break;
}
}
printf("%.1lf\n",ans*1.0/m);
while(1)getchar();
return 0;
}