Acwing 840. 模拟散列表(链表法模拟)

地址:https://www.acwing.com/problem/content/842/

 

解析:

关于MOD:一般要取质数 ,要离2的整次幂尽可能远,降低冲突概率,这里取1e5+3

对一个数取模后,如何处理冲突?这里就用到了链表,链表里只有一个头节点,而这里有很多头节点,h[]

每个结点,对应着一组链表,冲突数就存在里面。

插入时,按链从头节点的插入模板即可。

#include<cstdio>
#include<cstring>
#include<vector>
#include<set>
#include<stack>
#include<algorithm>
#include<iostream>
#include<vector>
using namespace std;
typedef long long ll;
const int maxn=1e5+3,maxn2=31*maxn;
int h[maxn],ne[maxn],e[maxn],idx;
void insert(int x)
{
    int k = (x%maxn+maxn)%maxn;
    e[idx]=x;
    ne[idx]=h[k];
    h[k]=idx++;
}
bool query(int x)
{
    int k = (x%maxn+maxn)%maxn;
    for(int i=h[k];i!=-1;i=ne[i])
        if(e[i]==x)
            return true;
        return false;
}
int main()
{
    int n;
    scanf("%d",&n);
    memset(h,-1,sizeof(h));
    while(n--)
    {
        char op[3];
        int x;
        scanf("%s%d",op,&x);
        if(op[0]=='I')
        {
            insert(x);
        }
        else
        {
            if(query(x))
                cout<<"Yes"<<endl;
            else
                cout<<"No"<<endl;
        }
    }
}

 

posted @ 2020-11-10 19:58  liyexin  阅读(141)  评论(0编辑  收藏  举报