哈希表
作者:
ysc
,
2021-07-28 11:06:13
,
所有人可见
,
阅读 255
开放寻址法
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 2e5+3, 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 T;
cin >> T;
while ( T -- )
{
char op[2];
int x;
cin >> op >> x;
if ( op[0] == 'I' ) h[find(x)] = x;
else
{
if ( h[find(x)] == null ) puts("No");
else puts("Yes");
}
}
return 0;
}
拉链法
#include <iostream>
#include <cstring>
using namespace std;
const int N = 1e5+10;
int h[N], e[N], ne[N], idx;
void add(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 T;
cin >> T;
memset(h, -1, sizeof h);
while ( T -- )
{
char op[2];
int x;
cin >> op >> x;
if ( op[0] == 'I' ) add(x);
else
{
if ( !find(x) ) puts("No");
else puts("Yes");
}
}
return 0;
}