题目描述
维护一个集合,支持如下几种操作:
I x
,插入一个数 x;Q x
,询问数 x 是否在集合中出现过;
现在要进行 N 次操作,对于每个询问操作输出对应的结果。
输入格式
第一行包含整数 N,表示操作数量。
接下来 N 行,每行包含一个操作指令,操作指令为 I x
,Q x
中的一种。
输出格式
对于每个询问指令 Q x
,输出一个询问结果,如果 x 在集合中出现过,则输出 Yes
,否则输出 No
。
每个结果占一行。
数据范围
1 ≤ N ≤ 1 0 5 , − 1 0 9 ≤ x ≤ 1 0 9 1≤N≤10^5, −10^9≤x≤10^9 1≤N≤105,−109≤x≤109
输入样例:
5
I 1
I 2
I 3
Q 2
Q 5
输出样例:
Yes
No
拉链法
#include<bits/stdc++.h>
#include <unordered_map>
using namespace std;
template <typename T> void debug(string s, T x) { cout << s << "=" << x << "\n"; }
typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll, ll>pll;
typedef pair<int, int>pii;
const ll N = 1e6 + 5;
const ll MOD = 1e9+7;
const ll INF = 0x7fffffff;
const int L=1e5+3;//拉链的长度一般取为第一大于要求长度的质数
int h[L];//槽
int e[N], ne[N], idx;//邻接表
void insert(int x) {
int k = (x % L + L) % L;//映射到0-L区间内
//头插法
e[idx] = x;//先将节点赋值
//h[k]为链头,存储的是第一个链表节点的下标
ne[idx] = h[k];//插入节点的指针指向链头节点
h[k] = idx++;//再将链头存储的值改为新插入节点的下标
}
bool find(int x) {
int k = (x % L + L) % L;
for (int i = h[k]; i != -1; i = ne[i]) {
if (e[i] == x)return true;
}
return false;
}
int main() {
ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
memset(h, -1, sizeof(h));//负一为空节点
int t;
cin >> t;
while (t--) {
string s;
int x;
cin >> s >> x;
if (s == "I") insert(x);
else {
if (find(x))cout << "Yes\n";
else cout << "No\n";
}
}
return 0;
}
开放寻址法
#include<bits/stdc++.h>
#include <unordered_map>
using namespace std;
template <typename T> void debug(string s, T x) { cout << s << "=" << x << "\n"; }
typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll, ll>pll;
typedef pair<int, int>pii;
const ll N = 1e6 + 5;
const ll MOD = 1e9+7;
const ll INF = 0x7fffffff;
//开放寻址法
const int L = 2e5+3;//存储空间一般要开到所需空间的2到3倍,取大于数据范围的第一个质数
const int null = 0x3f3f3f3f;//设一个比区间最大值大的作为空值
int h[L];
int get_pos(int x) {//如果存在则返回对应的位置,不存在则返回空
int k = (x % L + L) % L;
while (h[k] != null && h[k] != x) {
k++;
if (k == N)k = 0;
}
return k;
}
void insert(int k) {
h[get_pos(k)] = k;
}
bool find(int k) {
if (h[get_pos(k)] != null)return true;
return false;
}
int main() {
ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
memset(h, 0x3f, sizeof(h));//初始化为规定的空值
int t;
cin >> t;
while (t--) {
string s;
int x;
cin >> s >> x;
if (s == "I") insert(x);
else {
if (find(x))cout << "Yes\n";
else cout << "No\n";
}
}
return 0;
}