(1)拉链法
#include <cstring>
#include <iostream>
using namespace std;
const int N = 1e5 + 3;
int h[N], e[N], ne[N], idx;
void insert(int x)
{
int k = (x % N + N) % N;
e[idx] = x;
ne[idx] = h[k];
h[k] = idx++;
}
bool find(int x)
{
int k = (x % N + N) % N;
for (int i = h[k]; i != -1; i = ne[i])
{
if (e[i] == x)
{
return true;
}
}
return false;
}
int main()
{
int n;
cin >> n;
memset(h, -1, sizeof h);
while (n--)
{
string op;
int x;
cin >> op >> x;
if (op == "I")
{
insert(x);
}
else
{
if (find(x)) puts("Yes");
else puts("No");
}
}
return 0;
}
(2)开放寻址法
#include <cstring>
#include <iostream>
using namespace std;
const int N = 2e5 + 3;
const int null = 0x3f3f3f3f;
int h[N];
int find(int x)
{
int t = (x % N + N) % N;
while (h[t] != null && h[t] != x)
{
t++;
if (t == N)
{
t = 0;
}
}
return t;
}
int main()
{
int n;
cin >> n;
memset(h, 0x3f, sizeof h);
while (n--)
{
string op;
int x;
cin >> op >> x;
if (op == "I")
{
h[find(x)] = x;
}
else
{
if (h[find(x)] == null) puts("No");
else puts("Yes");
}
}
return 0;
}
#include<iostream>
#include<cstdio>
#include<string>
using namespace std;
typedef unsigned long long ULL;
const int N = 1e5+5,P = 131;
ULL h[N],p[N];
ULL query(int l,int r)
{
return h[r] - h[l-1]*p[r-l+1];
}
int main()
{
int n,m;
cin>>n>>m;
string str;
cin>>str;
p[0] = 1;
h[0] = 0;
for(int i=0;i<n;i++)
{
p[i+1] = p[i]*P;
h[i+1] = h[i]*P +str[i];
}
while(m--)
{
int l1,r1,l2,r2;
cin>>l1>>r1>>l2>>r2;
if(query(l1,r1) == query(l2,r2)) printf("Yes\n");
else printf("No\n");
}
return 0;
}