PAT-A1022.Digital Library

思路:
1、结构体book 存放书的信息
2、用ID作映射 map

/**************************
//@Author: 3stone
//@ACM: PAT-A1022.Digital Library
//@Time: 2018/1/25
//@IDE: VS2017
***************************/
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<string>
#include<cstring>
#include<map>
#include<set>

using namespace std;

typedef struct book{
    string info[10];//用info[1-5]表示除ID外的信息
    set<string> keyword; //保存切分后的 keyword
}book;

//查询函数一定要加上引用'&',否则最后一组测试点会超时
void searchID(int key, string str, map<string, book> &lib) {
    int count = 0;
    //搜索keyword需特殊处理,因为输入是一串,查询是要找其中一个
    if (key == 3) {
        for (map<string, book>::iterator it = lib.begin(); it != lib.end(); it++) {
            if (it->second.keyword.find(str) != it->second.keyword.end()) {
                count++;
                cout << it->first << endl;
            }
        }
        if (count == 0) cout << "Not Found" << endl;
    }
    else {
        for (map<string, book>::iterator it = lib.begin(); it != lib.end(); it++) {
            if (it->second.info[key] == str) {
                count++;
                cout << it->first << endl;
            }
        }
        if (count == 0) cout << "Not Found" << endl;
    }
}

//截取出keyword
void dealKeyword(string ID, map<string, book> &lib) { 
    //map 一定要加引用符 '&', 否则不改变main中map
    string str = lib[ID].info[3], word;
    for (int i = 0; i < str.size(); ) {
        if (str[i] == ' ') {
            word = str.substr(0, i);
            str.erase(0, i + 1); //擦去第一个单词
            lib[ID].keyword.insert(word);
            i = 0; 
        }
        else
            i++;
    }
    lib[ID].keyword.insert(str); // 千万别忘了最后的一个word
}

int main() {
    map<string, book> lib;  //map会按键值(ID)递增排序 
    int n, m;
    cin >> n; getchar();  //吸收换行符
    for (int i = 0; i < n; i++) { //获取数据
        string ID;
        getline(cin, ID);
        getline(cin, lib[ID].info[1]);
        getline(cin, lib[ID].info[2]);
        //输入keywords后需要处理,存入结构体中的set-keyword中
        getline(cin, lib[ID].info[3]);
        dealKeyword(ID, lib);
        getline(cin, lib[ID].info[4]);
        getline(cin, lib[ID].info[5]);
    }
    cin >> m; getchar(); //吸收换行符
    for (int j = 0; j < m; j++) { //输入一组查询,解决一组
        string query;
        getline(cin, query);
        cout << query << endl; //先输出原查询
        int key = query[0] - '0';
        query.erase(0, 3);
        searchID(key, query, lib);
    }

    system("pause");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_26398495/article/details/79167333