题目描述
哈希
算法1
开放寻址法
C++ 代码
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int N=2e5+3;
const int null=0x3f3f3f3f;
int h[N];
int find(int x)
{
int k;
k=(x%N+N)%N;
while(h[k]!=null &&h[k]!=x)
{
k++;
if(k==N) k=0;
}
return k;
}
int main()
{
int n;
memset(h,0x3f,sizeof h);
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("yes");
else cout<<"NO"<<endl;
}
}
return 0;
}
算法2
拉链法
C++ 代码
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int N=2e5+3;
int h[N],e[N],ne[N];
int idx;
bool find(int x)
{
int k;
k=(x%N+N)%N;
for(int i=h[k];i!=-1;i=ne[i])
{
if(e[i]==x) return true;
}
return false;
}
int insert(int x)
{
int k;
k=(x%N+N)%N;
e[idx]=x,ne[idx]=h[k],h[k]=idx++;
return 0;
}
int main()
{
int n;
memset(h,-1,sizeof h);
scanf("%d",&n);
while(n--)
{
char op[2];
int x;
scanf("%s%d",op,&x);
if(*op=='I') insert(x);
else{
if(find(x)) puts("yes");
else cout<<"NO"<<endl;
}
}
return 0;
}