PAT甲级1022.

目录

A1022

题目

样例

输入:

3
1111111
The Testing Book
Yue Chen
test code debug sort keywords
ZUCS Print
2011
3333333
Another Testing Book
Yue Chen
test code sort keywords
ZUCS Print2
2012
2222222
The Testing Book
CYLL
keywords debug book
ZUCS Print2
2011
6
1: The Testing Book
2: Yue Chen
3: keywords
4: ZUCS Print
5: 2011
3: blablabla

输出:

1: The Testing Book
1111111
2222222
2: Yue Chen
1111111
3333333
3: keywords
1111111
2222222
3333333
4: ZUCS Print
1111111
5: 2011
1111111
2222222
3: blablabla
Not Found

本题借鉴柳婼的解题思路。

思路和坑点

  对不同的查询信息,建立对应的存储表。不同的查询字对应不同的存储表,利用set的自身有序性和不重复的特征存储查询表,并使用map容器把每一类关键字映射到一个set容器,查询时应当先判定是否有该记录。
  读取每本书的信息,参见代码部分的读入。

AC代码

#include<bits/stdc++.h>
using namespace std;
unordered_map<string,set<int> > title,name,key,pu,py;               //查询要用到的索引表 
void getans(unordered_map<string,set<int> > &mp,string &check){     //查询函数,传引用,对不同的查询字进行查询 
    if(mp.find(check)==mp.end())                                    //如果找不到 
        puts("Not Found");
    else{
        for(auto it=mp[check].begin();it!=mp[check].end();it++)     //如果找到,则遍历输出,set自身有序 
            printf("%07d\n",*it);
    }
}
void getbook(){                                                     //读取一本书的记录 
    int id;
    string _title,_name,_key,_pu,_py;                                
    scanf("%d",&id);    getchar();                                  //读取id后,要过滤换行符 
    getline(cin,_title);    title[_title].insert(id);               //整行读取书名和人名 
    getline(cin,_name);        name[_name].insert(id);
    while(1){                                                       //分别读取关键词,并单独处理 
        cin>>_key;    key[_key].insert(id);        
        char ch=getchar();                                          //吸收空格,如果到了结尾的回车,关键字读取结束 
        if(ch=='\n')    break;
    }
    getline(cin,_pu);    pu[_pu].insert(id);                        //整行读取出版商和出版时间 
    getline(cin,_py);    py[_py].insert(id);
}
int main(void){
#ifdef ONLINE_JUDGE
#else
    freopen("1.txt","r",stdin);
#endif
    int n;
    scanf("%d",&n);    getchar();
    for(int i=0;i<n;i++){
        getbook();
    }
    scanf("%d",&n);    getchar();
    for(int i=0;i<n;i++){
        string str;
        getline(cin,str);                                           //整行读入查询语句 
        cout<<str<<'\n';
        string check=str.substr(3,str.size()-3);                    //摘取查询字 
        switch(str[0]){                                             //根据查询类型分类查询 
            case '1':getans(title,check);break;
            case '2':getans(name,check);break;
            case '3':getans(key,check);break;
            case '4':getans(pu,check);break;
            case '5':getans(py,check);break;
        }    
    }
    return 0;
}