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 
#include 
#include 
#include 
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;
}

  

 

你可能感兴趣的:(2019年浙江大学计算机复试上机 Unsuccessful Searches)