题目链接:1022 Digital Library
#include <iostream>
#include <unordered_map>
#include <vector>//换成set可能更好
#include <algorithm>
using namespace std;
class solution{
public:
unordered_map<string,vector<string>> mvi[5];//0:title, 1:author, 2:keyWord, 3:publisher, 4:year
void digitalLibrary(){
int n, m;
cin >> n;
scanBook(n);//扫描n本图书
cin >> m;
searchBook(m);//查找m次图书
}
private:
void scanBook(int n){
for(int i = 0; i < n; i++){
string id, s;
cin >> id;
getchar();
for(int j = 0; j <= 4; j++){
if(j != 2){
getline(cin, s);
mvi[j][s].push_back(id);
}
else{//输入关键字需特别处理
char c = '0';
while(c!='\n'){//以回车结尾时跳出循环
cin >> s;
mvi[j][s].push_back(id);
c = getchar();
}
}
}
}
}
void searchBook(int m){
char a;
string s;
getchar();//吸收上个操作遗留的回车
for(int i = 0; i < m; i++){
a = getchar();
getchar();//吸收冒号与空格
getchar();
int flag = 0 , b = a - '0' - 1;//flag:查找成功标记位,b:将char a转换为int b
getline(cin, s);
printf("%c: %s\n", a, s.c_str());
if(mvi[b].find(s) != mvi[b].end()){
flag = 1;
sort(mvi[b][s].begin(),mvi[b][s].end());//排序,如果是set就不需要排序了
for(auto it: mvi[b][s]) printf("%s\n",it.c_str());
}
if(!flag) printf("Not Found\n");
}
}
};
int main(){
solution s;
s.digitalLibrary();//建立数字图书馆
}