问题 B: 【哈希和哈希表】图书管理

时间限制: 1 Sec 内存限制: 128 MB

题面 提交 状态

题目描述

图书管理是一件十分繁杂的工作,在一个图书馆中每天都会有许多新书加入。为了更方便的管理图书(以便于帮助想要借书的客人快速查找他们是否有他们所需要的书),我们需要设计一个图书查找系统。

该系统需要支持 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

#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <string.h>
#include <queue>
#include <vector>
#include <map>
#include <cmath>
#include <stack>
using namespace std;
typedef long long ll;
typedef pair<ll,ll> pll;
map<pll,bool> mmap;
const pll k(1e9+9,1e9+321);
const pll p(1e9+7,1e9+9);
const pll one(1ll,1ll);
const pll 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 tmp = zero;
    for(int i=0;a[i]!='\n';i++)
        tmp = tmp*k + a[i];
    return tmp;
}
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(b[0]=='a')
            mmap[x] = true;
        else{
            mmap[x]?printf("yes\n"):printf("no\n");
        }
    }
    return 0;
}

留下评论

通过 WordPress.com 设计一个这样的站点
从这里开始