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 (≤103, 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 (≤104) 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