题目描述
维护一个集合,支持如下几种操作:
“I x”,插入一个数x;
“Q x”,询问数x是否在集合中出现过;
现在要进行N次操作,对于每个询问操作输出对应的结果。
输入格式
第一行包含整数N,表示操作数量。
接下来N行,每行包含一个操作指令,操作指令为”I x”,”Q x”中的一种。
输出格式
对于每个询问指令“Q x”,输出一个询问结果,如果x在集合中出现过,则输出“Yes”,否则输出“No”。
每个结果占一行。
数据范围
1≤N≤105
−109≤x≤109
样例
输入样例:
5
I 1
I 2
I 3
Q 2
Q 5
输出样例:
Yes
No
算法1
学习使用哈希散列表 C++标准库中也有该容器 unordered_map set等
C++ 代码
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
#include <set>
int n;
int main()
{
cin>>n;
set<int> str;
while(n--)
{
char op[2];
scanf("%s",op);
if(!strcmp(op,"I"))
{
int k;
cin>>k;
str.insert(k);
}
else
{
int k;
cin>>k;
if(str.count(k)!=0) cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
}
return 0;
}
2、拉链法
C++ 代码
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int N=1e5+10;
int n,idx;
int h[N],e[N],ne[N];
void insert(int x)
{
int k=(x%N+N)%N;
e[idx]=x,ne[idx]=h[idx],h[k]=idx++;
}
bool find(int x)
{
int k=(x%N+N)%N;
for(int i=h[k];i!=-1;i=ne[i])
{
if(i==-1) return false;
if(e[i]==x) return true;
}
return false;
}
int main()
{
memset(h,-1,sizeof h);
scanf("%d",&n);
int k;
while(n--)
{
char op[2];
scanf("%s",op);
if(*op=='I')
{
cin>>k;
insert(k);
}
else
{
cin>>k;
if(find(k)==true) cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
}
return 0;
}
3、开放寻址法
C++ 代码
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int N=1e5+10;
int h[N];
int n;
int find(int x)
{
int k=(x%N+N)%N;
while(h[k]!=-1&&h[k]!=x)
{
k++;
if(k==N) k=0;
}
return k;
}
int main()
{
memset(h,-1,sizeof h);
scanf("%d",&n);
int x;
while(n--)
{
char op[2];
scanf("%s",op);
if(*op=='I')
{
cin>>x;
int k=find(x);
h[k]=x;
}
else
{
cin>>x;
if(h[find(x)]==x) cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
}
return 0;
}