AcWing 840. 模拟散列表
原题链接
简单
作者:
码
,
2020-06-21 22:51:02
,
所有人可见
,
阅读 523
1.拉链法
#include<iostream>
#include<cstring>
using namespace std;
const int N=1e5+3;
int h[N],v[N],ne[N],idx;
void insert(int x)
{
int k=(x%N+N)%N;
v[idx]=x;
ne[idx]=h[k];
h[k]=idx++;
}
bool find(int x)
{
int k=(x%N+N)%N;
int i=h[k];
while(i!=-1 && v[i]!=x) i=ne[i];
if(v[i]==x) return true;
return false;
}
int main()
{
int n;
memset(h,-1,sizeof h);
cin>>n;
while(n--)
{
char op;
int x;
cin>>op;
cin>>x;
if(op=='I') insert(x);
else
{
if(find(x)) cout<<"Yes"<<endl;
else cout<<"No"<<endl;
}
}
return 0;
}
2.开放寻址法
#include<iostream>
#include<cstring>
using namespace std;
const int N=2e5+3;
int h[N],flag=0x3f3f3f3f;
int find(int x)
{
int k=(x%N+N)%N;
while(h[k]!=flag && h[k]!=x)
{
k++;
if(k==N) k=1;
}
return k;
}
int main()
{
int n;
memset(h,0x3f,sizeof h);
cin>>n;
while(n--)
{
char op;
int x;
cin>>op;
cin>>x;
if(op=='I') h[find(x)]=x;
else
{
if(h[find(x)]==x) cout<<"Yes"<<endl;
else cout<<"No"<<endl;
}
}
return 0;
}