7-3 Unsuccessful Searches (25分)

该博客讨论了如何使用哈希表和线性探测解决GRE-CS 2018年考试中的一道题目。内容涉及到计算在特定情况下,不成功搜索的平均时间。输入和输出规格以及样例数据给出了解题的格式要求。文章提醒读者注意散列函数和冲突处理函数的区别,并提供了两种不同的代码实现方法。
摘要由CSDN通过智能技术生成

在这里插入图片描述
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 H(key)=key%7, 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 (≤10​3​​, the table size), M (≤TSize, the divisor in the hash function), and N (≤TSize, the number of integers to be inserted). Then N non-negative integers (≤10​4​​) 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

Note: In sample 2, the last test of the original position counts as well.

  • 思路:哈希探测
    TIPS 1:散列函数和冲突处理函数不是一个!!!
    散列函数是第一次用来求pos: x % MSize , 即题中的 H(Key) = key % 7
    而冲突处理函数是针对表长的,可以散列到整张表中,nex = (pos + di) % TSize, 即题中的 nex = (pos + i ) % 11

TIPS 2: 注意审题!!! 题中non-negative!!!不是postive,可能有0插入表,所有初始应将table赋值为-1加以区别

  • T1 code: for()写法
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1010;
int table[maxn];

void InsertTable(int x, int MSize, int TSize)
{
   
    int pos = x % MSize;
    for(int i = 0; i < TSize; ++i
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值