PAT1022 Digital Library (30)(map的使用)

很简单的题,就是考察一个map的使用,不过这题有个陷阱就是最后输出的id必须是7位的,我做这题的时候用到了string的分割,其实不需要,直接用getchar()就可以判断结束条件,注意使用getline时要吃掉\n

#include<string>
#include<cstdlib>
#include<vector>
#include<stack>
#include<queue>
#include<utility>
#include<map>
#include<set>
#include<cstdlib>
#include<string.h>
#include<stdio.h>
#include<algorithm>
#include<functional>
#include<iostream>
#define INF 0x6ffff
using namespace std;

map<string, set<int>> title;
map<string, set<int>> author;
map<string, set<int>> keyword;
map<string, set<int>> publisher;
map<string, set<int>> year;

vector<string> split(const string &str, const string &pattern)
{
	//const char* convert to char*
	char * strc = new char[strlen(str.c_str()) + 1];
	strcpy(strc, str.c_str());
	vector<string> resultVec;
	char* tmpStr = strtok(strc, pattern.c_str());
	while (tmpStr != NULL)
	{
		resultVec.push_back(string(tmpStr));
		tmpStr = strtok(NULL, pattern.c_str());
	}

	delete[] strc;

	return resultVec;
}

void print(set<int> &res) {
	if (res.empty())
		cout << "Not Found" << endl;
	else {
		for (auto x : res)
			printf("%07d\n", x);
	}
}

int main() {
	int n,m;
	cin >> n;
	while (n--) {
		int id;
		string t, a, k, p,y;
		cin >> id;
		cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
		getline(cin, t);
		getline(cin, a);
		getline(cin, k);
		getline(cin, p);
		cin >> y;
		vector<string> key = split(k, " ");
		for (auto x : key)
			keyword[x].insert(id);
		title[t].insert(id);
		author[a].insert(id);
		publisher[p].insert(id);
		year[y].insert(id);
	}
	cin >> m;
	cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
	while (m--) {
		int num;
		scanf("%d: ", &num);
		string query;
		getline(cin, query);
		cout << num << ": " << query << endl;
		switch (num) {
		case 1:print(title[query]); break;
		case 2:print(author[query]); break;
		case 3:print(keyword[query]); break;
		case 4:print(publisher[query]); break;
		case 5:print(year[query]); break;
		}
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/seasonjoe/article/details/79836712