Hash table-zipper method and application examples

Hash table storage structure:
1. Open addressing method
2. Zipper method

The main function of the hash table:
to map a larger (0-10^9) data to a smaller (0-N (N is generally 10^5 to 10^6)) data

Hash function: can map a number from -10^19 to 10^19 to a number between 0-10^5

1. How to write a hash function?
Under normal circumstances, take the modulus directly, x%10^5, we generally take the number of the modulus as a prime number, and keep it as far away as possible from the whole power of 2, so that the probability of conflict is the smallest

2. Conflict: What should I do if I map two different numbers to the same number?
We can use open addressing method or zipper method to solve this problem

First, we first define the hash function: h(a) = b, which means that we map a to b.
Here we only introduce the zipper method.
Zipper Method:
Reference:
Graphical Algorithm
Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here

for example:

Maintaining a collection supports the following operations:
"I x", insert a number x;
"Q x", ask whether the number x has appeared in the collection;
now N operations are to be performed, and the corresponding output is output for each query operation result.

The first line of the input format
contains the integer N, which represents the number of operations.
Next N lines, each line contains an operation instruction, the operation instruction is one of "I x" and "Q x".

Output format
For each query instruction "Q x", output a query result. If x has appeared in the set, output "Yes", otherwise output "No".

Each result occupies one line.

Data range
1≤N≤105
−109≤x≤109

Input example:
5
I 1
I 2
I 3
Q 2
Q 5

Output example:
Yes
No

code show as below:

#include <iostream>
#include <cstring>
using namespace std;
const int N = 1e5+3;
int h[N],e[N],ne[N],idx;
void Insert(int x)
{
    
    
    int t = (x%N+N)%N;
    e[idx] = x;
    ne[idx] = h[t];
    h[t] = idx++;
    
}

bool find(int x)
{
    
    
    int t = (x%N+N)%N;
    for (int i = h[t];i!=-1;i = ne[i])
    {
    
    
        if (e[i]==x)
        {
    
    
            return true;
        }
    }
    return false;
}

int main()
{
    
    
    int cnt;
    cin>>cnt;
    memset(h,-1,sizeof(h));
    while(cnt--)
    {
    
    
        string a;
        int b;
        cin>>a>>b;
        if (a[0]=='I') Insert(b);
        else
        {
    
    
            if (find(b))
            {
    
    
                cout<<"Yes"<<endl;
            }
            else
            {
    
    
                cout<<"No"<<endl;
            }
        }
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/m0_51955470/article/details/114135191