2019年浙江大学计算机复试上机 Unsuccessful Searches

The above figure is a question from GRE-CS 2018. It states:

Given an initially empty hash table HT of size 11. The hash function is (, with linear probing used to resolve the collisions. Now hash the keys 87, 40, 30, 6, 11, 22, 98 and 20 one by one into HT. What is the average search time for unsuccessful searches?

The answer is 6.

Now you are supposed to write a program to solve this kind of problems.

Input Specification:

Each input file contains one test case. For each case, the first line gives 3 positive integers TSize (≤, the table size), M (≤, the divisor in the hash function), and N (≤, the number of integers to be inserted). Then N non-negative integers (≤) are given in the next line, separated by spaces.

Output Specification:

Print in a line the average search time for unsuccessful searches, after hashing the N integers into the table. The answer must be accurate up to 1 decimal place.

Sample Input 1:

11 7 8
87 40 30 6 11 22 98 20

Sample Output 1:

6.0

Sample Input 2:

3 3 3
81 2 5

Sample Output 2:

4.0


注意点:
1、算出插入位置是模表长, 不是模公式的数字
2、插入位置结束后,及时跳出
3、考试一般插入是 <号, 查询是<=, 重要
4、算查询不成功的次数,只算M个即可
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
using namespace std;
const int maxn = 1e3 + 10;
int p[maxn];
int main()
{
    memset(p, -1, sizeof(p));
    int Tsize, M, N, x;
    cin >> Tsize >> M >> N;
    for(int i = 0; i < N; i++){
        cin >> x;
        for(int j = 0; j < Tsize; j++){
            int pos = (x % M + j) % Tsize;
            if(p[pos] == -1){
                p[pos] = x;
                break;
            }
        }
    }
    double sum = 0;
    for(int i = 0; i < M; i++){
        for(int j = 0; j <= Tsize; j++){
            sum++;
            int pos = (i + j) % Tsize;
            if(p[pos] == -1){
                break;
            }
        }
    }
    printf("%.1f", sum / M);
    return 0;
}

  

 

转载于:https://www.cnblogs.com/thephoneix/p/11455689.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值