PAT Class A 1078 Hash

Link to original title

Insert an integer sequence composed of several different positive integers into a hash table, and then output the position of the input number.

A hash function is defined as H(key)=key%TSize, where TSize is the maximum size of the hash table.

Collisions are resolved using quadratic probing with only positive deltas.

Note that the size of the hash table is preferably a prime number, if the maximum size given by the user is not a prime number, the table size must be redefined to be the smallest prime number larger than the size given by the user.

Input Format
The first line contains two integers, MSize and N, representing the size of the user-defined table and the number of input numbers, respectively.

The second line contains N different positive integers separated by spaces.

Output format
In one line, output the corresponding position of each input number (index starts from 0), the numbers are separated by spaces, and there must be no extra spaces at the end of the line.

If a number cannot be inserted, - is output.

The data range is
1≤MSize≤104,
1≤N≤MSize, and
the input numbers are all in the range of [1,105].

Input example:
4 4
10 6 4 15
Output example:
0 1 4 -

My solution:

#include <bits/stdc++.h>
using namespace std;
const int N = 10010;
int h[N];
int s, n;
bool is_prime(int n){
    if(n == 1) return false;
    for(int i = 2; i * i <= n; i ++ ){
        if(n % i == 0) return false;
    }
    return true;
}

int find(int t){
    int k = t % s;
    for(int i = 0; i < s; i ++ ){
        int j = (k + i * i) % s;
        if(h[j] == 0) return j;
    }
    return -1;
}

int main(){
    cin >> s >> n;
    while(!is_prime(s)) s ++;
    

    for(int i = 0; i < n ; i ++ ){
        int x;
        cin >> x;
        
        int t = find(x);
        if(t == -1) cout << "-";
        else{
            h[t] = x;
            cout << t;
        }
        if(i != n - 1) cout << ' ';
    }
    return 0;
}

reward:

There are two ways for hash tables to resolve conflicts, the zipper method and the open addressing method. This question requires a  positive incremental secondary detection method , so that key + 1^2, key+2^2, and key+3^2 are sequentially searched for vacancies insert

Guess you like

Origin blog.csdn.net/weixin_45660485/article/details/126071129