我们来看一下题目:
不难看出,我们这道题可以直接用库函数中的哈希表来做。
在这之前让我们了解一下有关哈希表的库函数
- count(l):返回容器中值为 l 的元素数,如果容器中不存在值为 l 的元素,则返回 0。
2.emplace(l):向容器中添加新元素,传入的参数会被作为元素值进行插入操作,如果容器中已经存在相同元素,则什么也不做。
OK呀那么用他俩来实现一下
#include<bits/stdc++.h>
using namespace std;
unordered_set<string> s;
int n;string t,cmd;
int main(){
cin>>n;getchar();//用于去除add后,和find后的空格
for(int i=0;i<n;i++){
cin>>cmd;getline(cin,t);
if(cmd[0]=='a')s.emplace(t);
else
if(s.count(t)==1)cout<<"yes"<<endl; else cout<<"no"<<endl;
}
return 0;
}
这时候
有的聪明的同学就会问了
我们改如何在不用库函数的情况下,手打hash表来进行实现呢?
这时候就要请出我们的双hash思想了
我们用代码实现一下:
#include<bits/stdc++.h>
using namespace std;
const int b=13,M=30010;
int n;string t[M],cmd;int hed[1000001],nxt[M];
int h(string a){
int s=0;
for (int i=0;i<a.size();i++) s=(s*b+a[i]-'A'+1)%1000001;//此处用来求出一串字符的hash值并取模
return s;
}
bool insert(int s,int way){
int v=h(t[s]);
int u=hed[v];
while (u){
if (t[u]==t[s]) return true;
u=nxt[u];
}
if (way==1) return false;
nxt[s]=hed[v];hed[v]=s;
return true;
}//此处为链表,因为再取mod后,两值可能存在相等的情况,即hash值冲突,因此要用链表来解决。
int main(){
cin>>n;getchar();int ii=0;
for (int i=0;i<n;i++){
cin>>cmd;getchar();
getline(cin,t[++ii]);
if (cmd[0]=='a') insert(ii,0);
else{
if (insert(ii,1)) cout<<"yes"<<endl;
else cout<<"no"<<endl;
}
}
return 0;
}