传送门:模拟散列表
开放寻址法:将拥有相同余数的值都放到一段连续的区间,但堆积的太多会阻碍其他余数大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;
}