【算法笔记】A1022 Digital Library

题意

  输入n本书的信息:id,书名,作者,关键字,出版社,出版年份。搜索图书,输出id。

思路

  定义5个map<string, set<int> >,分别存放Title, Author, Word, Publishier, Year与id的映射关系,然后只需要考虑怎么输入就可以了。注意因为字符串和map的参数传递很慢,所以如果把查询写成函数,必须对参数进行引用,否则会导致运行超时。

code:

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 map<string, set<int> > Title, Author, Word, Publishier, Year;
 4 void query(map<string, set<int> > &mp, string &str){
 5     if(mp.find(str) == mp.end()) cout<<"Not Found"<<endl;
 6     else{
 7         for(set<int>::iterator it = mp[str].begin(); it!=mp[str].end(); it++){
 8             printf("%07d\n", *it);
 9         }
10     }
11 }
12 int main(){
13     int n, m, id, type;
14     string tit, aut, word, pub, year, search;
15     cin>>n;
16     for(int i = 0; i < n; i++){
17         cin>>id;
18         getchar();
19         getline(cin, tit);
20         Title[tit].insert(id);
21         getline(cin, aut);
22         Author[aut].insert(id);
23         while(cin>>word){
24             Word[word].insert(id);
25             char c = getchar();
26             if(c == '\n') break;
27         }
28         getline(cin, pub);
29         Publishier[pub].insert(id);
30         getline(cin, year);
31         Year[year].insert(id);
32     }
33     cin>>m;
34     for(int i = 0; i < m; i++){
35         scanf("%d: ", &type);
36         getline(cin, search);
37         cout<<type<<": "<<search<<endl;
38         if(type == 1) query(Title, search);
39         else if(type == 2) query(Author, search);
40         else if(type == 3) query(Word, search);
41         else if(type == 4) query(Publishier, search);
42         else if(type == 5) query(Year, search);
43     }
44     return 0;
45 }
posted @ 2019-04-27 09:17  Resfeber  阅读(440)  评论(0编辑  收藏  举报