问题 B: 【哈希和哈希表】图书管理
时间限制: 1 Sec 内存限制: 128 MB
提交: 25 解决: 9
[提交] [状态] [讨论版] [命题人:admin]
题目描述
图书管理是一件十分繁杂的工作,在一个图书馆中每天都会有许多新书加入。为了更方便的管理图书(以便于帮助想要借书的客人快速查找他们是否有他们所需要的书),我们需要设计一个图书查找系统。
该系统需要支持 2 种操作:
- add(s) 表示新加入一本书名为 s 的图书。
- find(s) 表示查询是否存在一本书名为 s 的图书。
输入
第一行包括一个正整数 n(n≤30000),表示操作数。 以下n行,每行给出 2 种操作中的某一个指令条,指令格式为:
add s
find s
在书名s与指令(add,find)之间有一个隔开,我们保证所有书名的长度都不超过200。可以假设读入数据是准确无误的。
输出
对于每个 find(s) 指令,我们必须对应的输出一行 yes 或 no,表示当前所查询的书是否存在于图书馆内。
注意:一开始时图书馆内是没有一本图书的。并且,对于相同字母不同大小写的书名,我们认为它们是不同的。
样例输入
4 add Inside C# find Effective Java add Effective Java find Effective Java
样例输出
no yes
有了双hash板子,这题就很简单了
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<ll,ll> pll;
map<pll,bool> M;
const pll k{1e9+9,1e9+321},p{1e9+7,1e9+9},one{1ll,1ll},zero{0ll,0ll};
pll operator - (pll a,pll b){return make_pair((a.first - b.first + p.first)%p.first,(a.second - b.second + p.second)%p.second);}
pll operator * (pll a,pll b){return make_pair((a.first * b.first)%p.first,(a.second * b.second)%p.second);}
pll operator + (pll a,pll b){return make_pair((a.first + b.first)%p.first,(a.second + b.second)%p.second);}
pll operator + (pll a,int b){return make_pair((a.first + b)%p.first,(a.second + b)%p.second);}
pll Hash(char a[]){
pll ans = zero;
for(int i=0;a[i]!='\n';i++)
ans = ans*k + a[i];
return ans;
}
char a[500],b[20];
int main(){
int n;
cin>>n;
while(n--){
cin>>b;
for(int i = 0;(a[i] = getchar())!='\n';i++);
pll x = Hash(a);
if(!strcmp(b,"add"))
M[x] = 1;
else
cout<<(M.count(x)? "yes" : "no")<<endl;
}
return 0;
}