题目连接在此。
题意:
给出n本书的信息(编号、书名、作者、关键字、出版社、出版年份),有m个一定格式的查询,如果在相应的书籍信息中找到了查询,则输出对应书的编号,否则输出“Not Found”。
思路:
将书本的信息(除编号之外)用一个类(bookInfo
)表示,然后用一个map<string,bookInfo>
变量tbl
表示书的编号到书本信息的映射,之后其实就是一个模拟的过程。
AC代码:
#include<stdio.h>
#include<iostream>
#include<string>
#include<vector>
#include<map>
using namespace std;
class bookInfo{ //书籍信息
public:
string title;
string author;
string keywords;
string publisher;
string year;
};
map<string, bookInfo> tbl; //bookID为key,bookInfo为value
int main(){
int n,m;
cin >> n;
for(int i = 0; i < n; i++){ //输入信息组数
string bookId;
bookInfo temp;
cin >> bookId; getchar();
getline(cin, temp.title);
getline(cin, temp.author);
getline(cin, temp.keywords);
getline(cin, temp.publisher);
getline(cin, temp.year);
tbl[bookId] = temp;
}
cin >> m; //查询数目
getchar();
for(int i = 0; i < m; i++){
string query;
getline(cin, query);
cout << query << endl;
int pos = query.find(" "); //找到到空格出现的位置
string type = query.substr(0,pos-1); //解析查询类型
query = query.substr(pos+1, query.length()-pos); //解析查询关键字
bool print = false; //是否找到并且打印标记
for(map<string, bookInfo>::iterator it = tbl.begin(); it != tbl.end(); it++){
bool flag = false; // 是否找到标记
if(type == "1"){
if(query == (it->second).title){
flag = true;
}
}else if(type == "2"){
if(query == (it->second).author){
flag = true;
}
}else if(type == "3"){
if(((it->second).keywords).find(query) != string::npos){
flag = true;
}
}else if(type == "4"){
if(query == (it->second).publisher){
flag = true;
}
}else if(type == "5"){
if(query == (it->second).year){
flag = true;
}
}else{
flag = false;
}
if(flag){ //如果找到了
cout << it->first << endl; //打印书籍编号
print = true; //置已经打印位为true
}
}
if(!print){ //若print==false,说明没打印过,即没找到
cout << "Not Found" << endl;
}
}
return 0;
}
注:
本题需要查询的其实是书本信息,而以上的思路则是将书本编号作为key。根据经验[1],将需要查询的变量作为key的时间复杂度一般来说会更小,也即将书籍的五种信息作为key,为每种信息定义一个map<string,set<int>>
变量,比如map<string,set<int>> tbl_title
,tbl_title
变量就是数书名到书籍编号的映射。那么可知需要五个这样的变量,其中keywords
信息需要一定的处理,将每个keyword
分离开来存放到map
变量中。
从题目给的数据看,上面给出的AC代码的思路的时间复杂度和书籍数量有关,而注中思路的时间复杂度则和书籍信息有关,时间复杂度是要小得多的(没做测试),并且在最后的输出控制上也要更为简单,代码的实现留给读者。
【1】此处所指经验可以参考:
PAT-A 1039. Course List for Student (25)
PAT-A 1047. Student List for Course (25)