散列表
开放寻址法
#include <iostream>
#include <cstring>
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()
{
memset(h, 0x3f,sizeof h);
int n;
cin >> n;
char op[2];
while (n -- )
{
int x;
scanf("%s", op);
scanf("%d", &x);
if (*op == 'I') h[find(x)] = x;
else if (h[find(x)] != null)
{
cout << "Yes" << endl;
}
else cout << "No" << endl;
}
return 0;
}
拉链法
#include <iostream>
#include <cstring>
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()
{
memset(h, -1,sizeof h);
int n;
cin >> n;
char op[2];
while (n -- )
{
int x;
scanf("%s", op);
scanf("%d", &x);
if (*op == 'I') insert(x);
else if (find(x))
{
cout << "Yes" << endl;
}
else cout << "No" << endl;
}
return 0;
}
hash表
#include <iostream>
using namespace std;
typedef unsigned long long ULL;
const int N = 1e5 + 10;
const int P = 131;
ULL h[N], p[N];
int n, m;
ULL query(int l, int r)
{
return h[r] - h[l - 1] * p[r - l + 1];
}
int main()
{
p[0] = 1;
cin >> n >> m;
char s[N];
scanf("%s", s + 1);
for (int i = 1; i <= n; i ++ )
{
h[i] = h[i - 1] * P + s[i];
p[i] = p[i - 1] * P;
}
while (m -- )
{
int l1, r1, l2, r2;
scanf("%d%d%d%d", &l1, &r1, &l2, &r2);
if (query(l1, r1) == query(l2, r2)) cout << "Yes" << endl;
else cout << "No" << endl;
}
return 0;
}