一、AcWing 840. 模拟散列表
【题目描述】
维护一个集合,支持如下几种操作:
I x
,插入一个数 x x x;Q x
,询问数 x x x是否在集合中出现过;
现在要进行 N N N次操作,对于每个询问操作输出对应的结果。
【输入格式】
第一行包含整数
N
N
N,表示操作数量。
接下来
N
N
N行,每行包含一个操作指令,操作指令为I x
,Q x
中的一种。
【输出格式】
对于每个询问指令Q x
,输出一个询问结果,如果
x
x
x在集合中出现过,则输出Yes
,否则输出No
。
每个结果占一行。
【数据范围】
1
≤
N
≤
1
0
5
1≤N≤10^5
1≤N≤105
−
1
0
9
≤
x
≤
1
0
9
-10^9≤x≤10^9
−109≤x≤109
【输入样例】
5
I 1
I 2
I 3
Q 2
Q 5
【输出样例】
Yes
No
【拉链法代码】
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
const int N = 100003;
int e[N], ne[N], h[N], idx;
int n, x;
string op;
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; i = ne[i])
if (e[i] == x) return true;
return false;
}
int main()
{
cin >> n;
memset(h, -1, sizeof h);
while (n--)
{
cin >> op >> x;
if (op == "I") insert(x);
else if (find(x)) cout << "Yes" << endl;
else cout << "No" << endl;
}
return 0;
}
【开放寻址法代码】
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
const int N = 200003;
const int INF = 0x3f3f3f3f;
int n, x, h[N];
string op;
//若存在x则返回x所在的位置,否则返回x应该插入的位置
int find(int x)
{
int k = (x % N + N) % N;
while (h[k] != x && h[k] != INF)
if (k++ > N) k = 0;
return k;
}
int main()
{
cin >> n;
memset(h, 0x3f, sizeof h);
while (n--)
{
cin >> op >> x;
int idx = find(x);
if (op == "I") h[idx] = x;
else if (h[idx] != INF) cout << "Yes" << endl;
else cout << "No" << endl;
}
return 0;
}