题目:https://pintia.cn/problem-sets/994805342720868352/problems/994805480801550336

这题应该算是最复杂的容器题之一了,用的是map >,实现了图书检索的效果
感觉不太会出这种题,对着算法笔记打了一遍代码理解了一下
注意一下第48、49行

代码

  1. #include<algorithm>
  2. #include<iostream>
  3. #include<vector>
  4. #include<cstdio>
  5. #include<map>
  6. #include<set>
  7. #include<string>
  8. using namespace std;
  9. map<string, set<int> > mpTitle, mpAuthor, myKey, mpPub, mpYear;
  10. void query(map<string, set<int> > &mp, string &str){
  11. if(mp.find(str) == mp.end()){//没找到关键词
  12. printf("Not Found\n");
  13. } else {
  14. for(auto it = mp[str].begin(); it != mp[str].end(); it++){
  15. printf("%07d\n", *it);
  16. }
  17. }
  18. }
  19. int main(){
  20. int n, m, type;
  21. string title, author, key, pub, year;
  22. scanf("%d", &n);
  23. for(int i = 0; i < n; i++){
  24. int tempid;
  25. scanf("%d", &tempid);
  26. char c = getchar();//吸收换行符
  27. getline(cin, title);
  28. mpTitle[title].insert(tempid);
  29. getline(cin, author);
  30. mpAuthor[author].insert(tempid);
  31. while(cin >> key){
  32. myKey[key].insert(tempid);
  33. c = getchar();
  34. if(c == '\n') break;
  35. }
  36. getline(cin, pub);
  37. mpPub[pub].insert(tempid);
  38. getline(cin, year);
  39. mpYear[year].insert(tempid);
  40. }
  41. string temp;
  42. scanf("%d",&m);
  43. for(int i = 0; i < m; i++){
  44. scanf("%d: ",&type);
  45. getline(cin, temp);
  46. cout<<type<<": "<<temp<<endl;
  47. if(type == 1) query(mpTitle, temp);
  48. else if(type == 2) query(mpAuthor, temp);
  49. else if(type == 3) query(myKey, temp);
  50. else if(type == 4) query(mpPub,temp);
  51. else if(type ==5) query(mpYear, temp);
  52. }
  53. return 0;
  54. }