【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;
}
总结
输入时会需要一些技巧
-
cin
和getline()
搭配使用时中间石视情况加上getchar()
,从而防止getline
读取换行符。 -
对于一行多串的情况可以
cin
配合getchar
使用。
while (cin >> tkey)
{
// do sth to tkey
char c = getchar();
if (c == '\n')
break;
}