「一本通 2.1 例 2」图书管理 (loj10034)

题目描述

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

该系统需要支持 2 种操作:

  1. add(s) 表示新加入一本书名为 s 的图书。
  2. find(s) 表示查询是否存在一本书名为 s 的图书。

输入格式

第一行包括一个正整数 n,表示操作数。 以下 n 行,每行给出 2 种操作中的某一个指令条,指令格式为:

add s
find s

在书名 s 与指令(addfind)之间有一个隔开,我们保证所有书名的长度都不超过 200。可以假设读入数据是准确无误的。

输出格式

对于每个 find(s) 指令,我们必须对应的输出一行 yesno,表示当前所查询的书是否存在于图书馆内。

注意:一开始时图书馆内是没有一本图书的。并且,对于相同字母不同大小写的书名,我们认为它们是不同的。

样例

样例输入

4
add Inside C#
find Effective Java
add Effective Java
find Effective Java

样例输出

no
yes

数据范围与提示

n≤30000

#include<cstdio>
#include<iostream>
#include<vector>
#include<string>
using namespace std;
vector <string> hash[300010];
int n;
int hashval(string s){
    int x = 0;
    for(int i = 0; i < (int)s.size(); ++i)
        x = (x * 120 + s[i]) % 300007;
    return x;        
}
string getst(){
    string x = "";
    char ch = getchar();
    while(ch != '\n'){
        x = x + ch;
        ch = getchar();
    }
    return x;
}
int main(void)
{
    cin >> n;
    for(int i=1; i<=n; ++i){
        string s;
        string book;
        cin >> s;
        book = getst();
        if(s == "add")
            hash[hashval(book)].push_back(book);
        else{
            int t = hashval(book), flag = 0;
            for(int i=0; i<(int)hash[t].size(); ++i)
                if(book == hash[t][i])    
                    flag = 1;
            if(flag)    cout << "yes" << endl;
            else        cout << "no"  << endl;
        }    
    }
}

思路:

  hash表存储图书名称,使用string进行比较搜索

猜你喜欢

转载自www.cnblogs.com/junk-yao-blog/p/9470251.html
今日推荐