图书管理

GitHub跳转原题关系图返回列表

用 unordered_set 维护图书集合,add 插入,find 查询。

OJ: roj

题目 ID: 1456

难度:入门

标签:字符串哈希表

创建: 2026-09-30 11:39

更新: 2026-10-06 00:13

题目描述

维护一个动态字符串集合,初始为空。依次处理 nn 条指令:add s 表示加入书名为 ss 的书,find s 表示查询是否存在该书。书名可能包含空格,区分大小写。对每个 find 输出 yes 或 no。

思路

用 unordered_set<string> 保存已添加的书名,add 时插入,find 时直接判断是否存在;每行读取时先读操作符,再用 getline 读取剩余内容作为书名。

参考代码

Python 版:

python
#!/usr/bin/env python3
# Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
# rbook: -> https://rbook.roj.ac.cn  https://rbook2.roj.ac.cn
# rainboy的学习导航网站: https://idx.roj.ac.cn
# create_at: 2026-09-30 11:39
# update_at: 2026-09-30 11:41

import sys
from collections.abc import Iterator


def execute_commands(commands: Iterator[str]) -> Iterator[str]:
    """处理图书馆操作序列,返回查询指令对应的结果流。"""
    library: set[str] = set()
    for line in commands:
        op, title = line.split(" ", 1)
        if op == "add":
            library.add(title)
        else:
            yield "yes" if title in library else "no"


def solve() -> None:
    lines = sys.stdin.read().splitlines()
    if not lines:
        return
    n = int(lines[0])
    command_lines = iter(lines[1 : n + 1])
    print("\n".join(execute_commands(command_lines)))


if __name__ == "__main__":
    solve()

C++ 版(同一算法):

cpp
/**
 * Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
 * rbook: -> https://rbook.roj.ac.cn  https://rbook2.roj.ac.cn
 * rainboy的学习导航网站: https://idx.roj.ac.cn
 * create_at: 2026-10-06 00:12
 * update_at: 2026-10-06 00:12
 */
#include <iostream>
#include <string>
#include <unordered_set>
using namespace std;

typedef long long ll;

unordered_set<string> book_set; // 存储已添加的图书名称
int n;
string op, s;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    cin >> n;
    string leftover;
    getline(cin, leftover); // 吃掉 n 后面的换行

    for (int i = 1; i <= n; i++) {
        cin >> op;
        getline(cin, s);
        // 去掉 op 与书名之间的那个空格
        if (!s.empty() && s[0] == ' ') {
            s.erase(0, 1);
        }

        if (op == "add") {
            book_set.insert(s);
        } else if (op == "find") {
            if (book_set.count(s)) {
                cout << "yes\n";
            } else {
                cout << "no\n";
            }
        }
    }

    return 0;
}