该题主要考察哈希表的使用
直接看代码~~~
#include<bits/stdc++.h>
using namespace std;
//分别存储五种属性,键为属性,值为ID
map<string, set<string>> k1;
map<string, set<string>> k2;
map<string, set<string>> k3;
map<string, set<string>> k4;
map<string, set<string>> k5;
int main() {
int N, M;
cin >> N;
cin.ignore(); // 去除\n,防止getline出现问题
for (int i = 0; i < N; i++) {
string ID, title, author, key, publisher, year;
getline(cin, ID); //输入
getline(cin, title);
getline(cin, author);
getline(cin, key);
getline(cin, publisher);
getline(cin, year);
//除了关键字key以外的属性,可以直接插入到哈希表中
k1[title].insert(ID);
k2[author].insert(ID);
//key,因为key这一行可能由多个关键字组成,所以要分割
key.push_back(' '); //末尾加一个空格便于分割
int pre = 0;
for (int j = 0; j < key.size(); j++) {
if (key[j] == ' ') { //遇到空格
string s = key.substr(pre, j - pre); //分割出一个关键字
k3[s].insert(ID); //插入到哈希表中
pre = j + 1; //更新pre
}
}
k4[publisher].insert(ID);
k5[year].insert(ID);
}
cin >> M;
cin.ignore();
for (int i = 0; i < M; i++) {
string query; //查询
getline(cin, query);
char way = query[0]; //查询的属性是字符串的第1位
string info = query.substr(3); //具体的key是从第3位开始的
cout << query << endl;
switch(way) { //各种查询方式
case '1': {
if(k1.count(info) == 0) //为空,不存在
cout << "Not Found" << endl;
else
for (auto & x : k1[info]) { //输出ID,set自动排序
cout << x << endl;
}
break;
}
case '2': {
if(k2.count(info) == 0)
cout << "Not Found" << endl;
else
for (auto & x : k2[info]) {
cout << x << endl;
}
break;
}
case '3': {
if(k3.count(info) == 0)
cout << "Not Found" << endl;
else
for (auto & x : k3[info]) {
cout << x << endl;
}
break;
}
case '4': {
if(k4.count(info) == 0)
cout << "Not Found" << endl;
else
for (auto & x : k4[info]) {
cout << x << endl;
}
break;
}
case '5': {
if(k5.count(info) == 0)
cout << "Not Found" << endl;
else
for (auto & x : k5[info]) {
cout << x << endl;
}
break;
}
}
}
return 0;
}