AcWing 840. 模拟散列表

拉链法

#include<cstring>
#include<iostream>
using namespace std ;
const int N=100003;
int h[N],e[N],ne[N],idx;
void insert(int x) {
    int k=(x%N+N)%N;//哈希函数
    //模拟单链表
    e[idx]=x;//先存下来
    ne[idx]=h[k];//指向负1
    h[k]=idx++;//原来的数字指向idx
}
bool find(int x) {
    int k=(x%N+N)%N;
    for(int i=h[k]; i!=-1; i=ne[i]) {
        if(e[i]==x)    return true;
    }
    return false;
}
int main() {
    int n;
    cin>>n;
    memset(h,-1,sizeof h);
    while(n--) {
        char op[2];
        int x;
        cin>>op>>x;
        if(*op=='I') insert(x);
        else {
            if(find(x)) cout<<"Yes"<<endl;
            else cout<<"No"<<endl;
        }
    }
    return 0;
}

开放寻址法

#include <cstring>
#include <iostream>
using namespace std;
const int N = 200003, null = 0x3f3f3f3f;
int h[N];
int find(int x) {
    int t = (x % N + N) % N;//哈希函数 
    while (h[t] != null && h[t] != x) { //如果被插入过且不为x 
        t ++ ;//往下接着找 
        if (t == N) t = 0;//找到头了,从头开始 
    }
    return t;//直到找到为止 
}
int main() {
    memset(h, 0x3f, sizeof h);
    int n;
    scanf("%d", &n);
    while (n -- ) {
        char op[2];
        int x;
        scanf("%s%d", op, &x);
        if (*op == 'I') h[find(x)] = x;
        else {
            if (h[find(x)] == null) puts("No");//如果没有插入过 
            else puts("Yes");
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/QingyuYYYYY/p/11828724.html