PAT甲级1145 Hashing - Average Search Time (25分)|C++实现

一、题目描述

原题链接
在这里插入图片描述

Input Specification:

在这里插入图片描述

​​Output Specification:

在这里插入图片描述

Sample Input:

4 5 4
10 6 4 15 11
11 4 15 2

Sample Output:

15 cannot be inserted.
2.8

二、解题思路

考察了哈希表解决冲突的平方探测法,按照题目给的步骤进行模拟即可,代码比较易读,详情见代码注释。

三、AC代码

#include<iostream>
#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;
int Tsize, N, M;
bool isPrime(int a) //判断一个数是否为素数
{
    
    
    if(a == 1 || a == 0)    return false;
    for(int i=2; i*i<=a; i++)
        if(a%i == 0)    return false;
    return true;
}
int main()
{
    
    
    int tmp;
    scanf("%d%d%d", &Tsize, &N, &M);
    while(!isPrime(Tsize))  Tsize++;    //将size设置为大于原来数字的最小素数
    bool exist[Tsize] = {
    
    false};    //标记是否冲突
    int Hash[Tsize] = {
    
    0};
    for(int i=0; i<N; i++)
    {
    
    
        scanf("%d", &tmp);
        bool inserted = false;  //标记是否成功插入
        int pos;
        for(int j=0; j<Tsize; j++)
        {
    
    
            pos = (tmp+j*j)%Tsize;  //平方探测
            if(!exist[pos])
            {
    
    
                Hash[pos] = tmp;
                exist[pos] = true;
                inserted = true;
                break;
            }
        }
        if(!inserted)   printf("%d cannot be inserted.\n", tmp);    //没有插入成功直接打印
    }
    int cnt = 0;
    for(int i=0; i<M; i++)
    {
    
    
        scanf("%d", &tmp);
        int pos;
        for(int j=0; j<=Tsize; j++)
        {
    
    
            pos = (tmp + j*j)%Tsize;
            cnt++;  //每循环一次 次数+1
            if(Hash[pos] == tmp || Hash[pos] == 0)    break;
        }
    }
    printf("%.1f\n", cnt*1.0/M);    //计算平均次数
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42393947/article/details/109080686
今日推荐