原題連結:1022 Digital Library (30分)
題目大意:
一本書,隻有一位作者,包含的關鍵詞不超過 5 個。
總共不超過 1000 個不同的關鍵詞,不超過 1000 個不同的出版商。
圖書資訊介紹完畢後,有一行包含一個整數 M,表示查詢次數。
當讀者查詢某一關鍵資訊時,你應該找到所有與查詢相關的書籍,并将它們按 ID 的升序排序輸出。
分析:
難點和重點在于:對字元串的讀入和處理。
有格式的字元串用 scanf() 比較好
普通無空格字元串用cin
包含空格的字元串用 getline(),且注意用 getchar 讀上一行剩下的回車
一行有未知數目的字元串,要用 stringstream
如本題中的圖書關鍵詞:
vector<string> keywords;
string keyword;
string line;
getline(cin, line)
stringstream ssin(line)
while(ssin >> keyword) {
keywords.insert(keyword)
}
這樣,就将 line 分割成單個 keyword 存入 keywords 中了。
其次是對查找進行處理:
首先,對讀入的問題進行輸出,然後用 string 的 substr 切割後邊的問題,用第 0 個字元判斷提問。将每次将符合條件的 id insert 到 set < string > 中,預設就是升序排列的。
滿分代碼:
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <set>
#include <sstream>
#define inf 0x3f3f3f3f
typedef long long LL;
using namespace std;
const int MAXN = 1e3+10;
struct Book {
string id, name, author;
set<string> keywords;
string publisher, year;
};
int main() {
int n, m;
cin >> n;
vector<Book> books;
for(int i = 0; i < n; i++) {
string id, name, author;
set<string> keywords;
string keyword, publisher, year;
cin >> id;
getchar();
getline(cin, name);
getline(cin, author);
// 一行讀分 将一行的多個字元串 分隔成單個字元串
string line;
getline(cin, line);
stringstream ssin(line);
while(ssin >> keyword) {
keywords.insert(keyword);
}
getline(cin, publisher);
cin >> year;
books.push_back({id, name, author, keywords, publisher, year});
}
cin >> m;
getchar();
string que;
while(m--) {
// 在使用getline()之前要讀入上一行的回車
getline(cin, que);
cout << que << endl;
string info = que.substr(3);
set<string> ids;
if(que[0] == '1') {
for(auto& p: books) {
if(p.name == info) {
ids.insert(p.id);
}
}
}
else if(que[0] == '2') {
for(auto& p: books) {
if(p.author == info) {
ids.insert(p.id);
}
}
}
else if(que[0] == '3') {
for(auto& p: books) {
if(p.keywords.count(info)) {
ids.insert(p.id);
}
}
}
else if(que[0] == '4') {
for(auto& p: books) {
if(p.publisher == info) {
ids.insert(p.id);
}
}
}
else if(que[0] == '5') {
for(auto& p: books) {
if(p.year == info) {
ids.insert(p.id);
}
}
}
// sort(ids.begin(), ids.end());
if(!ids.size()) {
cout << "Not Found" << endl;
} else {
for(auto & k: ids) {
cout << k << endl;
}
}
}
return 0;
}