PAT A1022 Digital Library (30point(s))

Links
to topics Note:
1. Map <string, set> is used to map student numbers to different string information for easy search.
2. The extraction of keywords should pay attention to distinguish between spaces and newlines. Only when newlines are encountered will the keyword part end. You can use getchar () to judge, the code is as follows:

do{//关键字要特殊处理
            cin>>key;//读入一个关键字
            mpkeywords[key].insert(id);//把id加入到key对应的集合中
        }while(getchar()!='\n');//只要不遇到换行符就说明还有关键字

3. If the query is completed with a function, pay attention to adding references to the mapping and the string, otherwise the transfer speed by parameter copying is very slow, and the last sample will time out.
4. After entering the id, use getchar () to absorb the newline, and the rest of the information with spaces should be entered using getline ().

#include<cstdio>
#include<map>
#include<string>
#include<iostream>
#include<set>
using namespace std;
map<string,set<int> > mptitle,mpauthor,mpkeywords,mppublisher,mpyear;//
string title,author,key,publisher,year;
void check(map<string,set<int> >& mp,string& query){
    //查询函数,为省时要使用引用
    if(mp[query].size()){//有对应的学号
            for(set<int>::iterator it=mp[query].begin();it!=mp[query].end();it++){
                printf("%07d\n",*it);//输出固定位数的号码不够的位也要用0补齐
            }
        }
        else cout<<"Not Found"<<endl;
}
int main(){
    int n,m;
    scanf("%d",&n);//书本数
    for(int i=0;i<n;i++){//信息录入
        int id;
        string info;
        scanf("%d",&id);
        char c=getchar();//接受掉学号一行的换行
        getline(cin,title);//书名
        mptitle[title].insert(id);//把id加入到title对应的集合中
        getline(cin,author);//作者名
        mpauthor[author].insert(id);//把id加入到author对应的集合中
        do{//关键字要特殊处理
            cin>>key;//读入一个关键字
            mpkeywords[key].insert(id);//把id加入到key对应的集合中
        }while(getchar()!='\n');//只要不遇到换行符就说明还有关键字
        getline(cin,publisher);//出版商
        mppublisher[publisher].insert(id);//将id加入到publisher对应的集合中
        getline(cin,year);//年份
        mpyear[year].insert(id);//将id加入到year对应的集合中
    }
    scanf("%d",&m);//查询数
    for(int i=0;i<m;i++){
        int querynum;//查询类型
        string query;//查询信息
        scanf("%d: ",&querynum);
        getline(cin,query);
        cout<<querynum<<": "<<query<<endl;
    if(querynum==1) check(mptitle,query);
    //不同的查询类型对应不同的映射
    else if(querynum==2) check(mpauthor,query);
    else if(querynum==3) check(mpkeywords,query);
    else if(querynum==4) check(mppublisher,query);
    else check(mpyear,query);
    }
    return 0;
}
Published 81 original articles · Like0 · Visitors644

Guess you like

Origin blog.csdn.net/weixin_44546393/article/details/105612392