hash——模拟散列表(拉链法和开放寻址法)

传送门:模拟散列表

开放寻址法:将拥有相同余数的值都放到一段连续的区间,但堆积的太多会阻碍其他余数大1的值的存放如

5
I 1
I 200011
I 400021
I 2
I 600031
在数组中的顺序。
1 200011 400021 2 600031

代码:

#include<iostream>
#include<algorithm>
#include<cstring>
#include<set>
#include<map>
using namespace std;
const int N=2e5+3,null=0x3f3f3f3f;
int h[N];//数组要开成给定数据范围的数倍
int find(int x)
{
    int k=(x%N+N)%N;
    while(h[k]!=null&&h[k]!=x)
    {
        k++;
        if(k==N) k=0;//查到尾部时要从头开始
    }
    return k;
}
int main()
{
    int n;
    cin>>n;
    memset(h,null,sizeof h);
    for(int i=1;i<=n;i++)
    {
        int x;
        char str[2];
        scanf("%s%d",str,&x);
        int k=find(x);
        if(str[0]=='I')
        {
            h[k]=x;
        }else
        {
            if(h[k]!=null) cout<<"Yes"<<endl;
            else cout<<"No"<<endl;
        }
    }
        return 0;
}

拉链法:

思路:具有相同余数的都放到同一条链表上

代码:

#include<iostream>
#include<algorithm>
#include<cstring>
#include<set>
#include<map>
using namespace std;
const int N=1e5+10,null=0x3f3f3f3f;
int h[N],e[N],ne[N],idx;//因为是以邻接表的形式存,不需要开数倍
void find(int x)
{
    int k=(x%N+N)%N;
    e[idx]=x,ne[idx]=h[k],h[k]=idx++;
}
bool get(int x)
{
    int t=(x%N+N)%N;
    for(int i=h[t];i!=-1;i=ne[i])
    {
        int j=e[i];
        if(j==x)
            return true;
    }
    return false;
}
int main()
{
    int n;
    cin>>n;
    memset(h,-1,sizeof h);
    for(int i=1;i<=n;i++)
    {
        int x;
        char str[2];
        scanf("%s%d",str,&x);

        if(str[0]=='I')
        {
            find(x);
        }else
        {
            if(get(x)) cout<<"Yes"<<endl;
            else cout<<"No"<<endl;
        }
    }
        return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值