【PAT甲级题解记录】1022 Digital Library (30 分)

【PAT甲级题解记录】1022 Digital Library (30 分)

前言

Problem:1022 Digital Library (30 分)

Tags:map映射

Difficulty:剧情模式 想流点汗 想流点血 死而无憾

Address:1022 Digital Library (30 分)

问题描述

给定一些书的数据,包括书名,编号,作者等等,然后再输入一些关键字,把所有符合的书的编号输出来即可。

解题思路

  • 一开始还写了个结构体来存储,后来发现只需要输出对应的id序列,那就简单了,用一个string为键、string的数组为值的map就可以了。

  • map中,键是我们query时属于的title、author等信息,而值就是对应的id序列。我们有5类query,那这样的map就需要5个,定义为一个map数组即可。

参考代码

#include<iostream>
#include<vector>
#include<algorithm>
#include<map>

using namespace std;


string id, title, author, key_word;
string publisher, pub_time;
map<string, vector<string>> to_books[6]; // 为了方便,定义6个,这样可以直接访问 1-5(忽略0)
int N; //  total number of books.
int M;

void init() {
    cin >> N;
    for (int i = 0; i < N; i++) {
        cin >> id;

        getchar();
        getline(cin, title);
        to_books[1][title].push_back(id);

        getline(cin, author);
        to_books[2][author].push_back(id);

        string key;
        while (cin >> key) {
            to_books[3][key].push_back(id);
            if (getchar() == '\n') break;
        }

        getline(cin, publisher);
        to_books[4][publisher].push_back(id);

        cin >> pub_time;
        to_books[5][pub_time].push_back(id);

    }
}

void solve() {
    cin >> M;
    getchar();
    while (M--) {
        string s;
        getline(cin, s);
        int order = s[0] - '0';
        string query = s.substr(3);
        cout << order << ": " << query << endl;
        vector<string> ans = to_books[order][query];
        if (int(ans.size()) == 0) {
            cout << "Not Found" << endl;
            continue;
        }
        sort(ans.begin(), ans.end());
        for (int i = 0; i < int(ans.size()); ++i) {
            cout << ans[i] << endl;
        }
    }
}

void solution_1022() {
    init();
    solve();
}

int main() {
    solution_1022();
    return 0;
}

总结

输入时会需要一些技巧

  • cingetline()搭配使用时中间石视情况加上getchar(),从而防止getline读取换行符。

  • 对于一行多串的情况可以cin配合getchar使用。

    while (cin >> tkey)
    {
        // do sth to tkey
        char c = getchar();
        if (c == '\n')
            break;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值