题目
A Digital Library contains millions of books, stored according to their titles, authors, key words of their abstracts, publishers, and published years. Each book is assigned an unique 7-digit number as its ID. Given any query from a reader, you are supposed to output the resulting books, sorted in increasing order of their ID’s.
分析
这是一道查询的题目,给出一个ID,该ID下对应一本书和该书的信息:书名,作者,关键词(多个),出版商,出版年份。现在要你根据查询的指令:1、2、3、4、5,分别代表书名、作者、一个关键词、出版商、出版年份,根据给出的信息输出与之对应的ID,若对应多个ID则递增排序输出,若没有相对应的ID则输出“Not Found”。
解题思路
*1顺应要求的输出,所以我们应当建立一个以查询信息为key的容器,该容器装着对应的ID,这样就舒服了。
*2所以这里考察既有对应关系又有容器关系,就是STL里map和set的混合使用啦!
*3先来复习一下map和set的使用:
- map 创建:map<type1, type2> name;
- map 初始化:name[n1] = n2;
- map 键的查找:name.find(n1);(若找不到会取到末尾)
- map 起始与末尾:name.begin(), name.end();
- set 创建:set name;
- set 插入:name.insert(x);
- set 起始与末尾:name.begin(), name.end();
值得注意的是对应set里面的元素是会自动去重和递增排序的,我们可以很好的利用这一特性去解决更多的题。
最后直接上代码:
#include<iostream>
#include<map>
#include<set>
using namespace std;
map<string, set<int> > title, author, key, pub, year;
void query(map<string, set<int> > &m, string &str)
{
if(m.find(str) != m.end())
{
for(auto it = m[str].begin(); it != m[str].end(); it++)
{
printf("%07d\n", *it);
}
}
else printf("Not Found\n");
}
int main()
{
int n, id, num; scanf("%d", &n);
string ttitle, tauthor, tkey, tpub, tyear;
for(int i = 0; i < n; i++)
{
scanf("%d\n", &id);
getline(cin, ttitle);
title[ttitle].insert(id);
getline(cin, tauthor);
author[tauthor].insert(id);
while(cin >> tkey)
{
key[tkey].insert(id);
char c;
c = getchar();
if(c == '\n') break;
}
getline(cin, tpub);
pub[tpub].insert(id);
getline(cin, tyear);
year[tyear].insert(id);
}
int m; scanf("%d", &m);
string temp;
for(int i = 0; i < m; i++)
{
scanf("%d: ", &num);
getline(cin, temp);
printf("%d: %s\n", num, temp.c_str());
if(num == 1) query(title, temp);
else if(num == 2) query(author, temp);
else if(num == 3) query(key, temp);
else if(num == 4) query(pub, temp);
else query(year, temp);
}
return 0;
}
小结
- 重温了STL里map和set的妙用,搭配使用好用到爆。
- 关于输入的手法一般有scanf和cin或者getline以及getchar(),要综合利用其特性去解题,像本题中利用scanf把"\n"给吸收掉以及利用cin的不收空格符,getchar()的全收,完美解决关于keyword的输入。
- 函数思维是编程很重要的思想,凡事多往这边靠,成功指日可待。
还有什么问题,我们一起讨论吧~