PAT (Advanced Level) Practice A1022 Digital Library (30 分)(C++)(甲级)(map,由string向set的映射)

版权声明:假装有个原创声明……虽然少许博文不属于完全原创,但也是自己辛辛苦苦总结的,转载请注明出处,感谢! https://blog.csdn.net/m0_37454852/article/details/86665123

原题链接:1022 Digital Library

#include<algorithm>
#include<iostream>
#include<cstdio>
#include<cstring>
#include <set>
#include <map>
using namespace std;

map<string, set<int> > Title, Author, KeyWords, Publisher, Year;//字符串向集合的映射

void print(map<string, set<int> >& MAP, string& str)//不加引用会超时,字符串及map的形参传递较慢
{
    if(MAP.find(str) == MAP.end()) printf("Not Found\n");
    else
    {
        for(set<int>::iterator it = MAP[str].begin(); it != MAP[str].end(); it++)
        {
            printf("%07d\n", *it);
        }
    }
}

int main()
{
    int N, M, ID;
    string str;
    scanf("%d", &N);
    for(int i=0; i<N; i++)
    {
        scanf("%d", &ID);
        getchar();
        getline(cin, str), Title[str].insert(ID);
        getline(cin, str), Author[str].insert(ID);
        while(1)//关键字使用空格分割,分多次接收
        {
            cin>>str;
            KeyWords[str].insert(ID);
            if(getchar() == '\n') break;
        }
        getline(cin, str), Publisher[str].insert(ID);
        getline(cin, str), Year[str].insert(ID);
    }
    scanf("%d", &M);
    for(int i=0; i<M; i++)
    {
        int num;
        scanf("%d: ", &num);//接收前面的数字
        getline(cin, str);//接收后面输入的字符串进行搜索
        cout<<num<<": "<<str<<endl;
        if(num == 1) print(Title, str);
        else if(num == 2) print(Author, str);
        else if(num == 3) print(KeyWords, str);
        else if(num == 4) print(Publisher, str);
        else print(Year, str);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/m0_37454852/article/details/86665123