题目 PAT A 1022
题目大意
有n
本书,每本书输入的格式为
Line #1: the 7-digit ID number;
Line #2: the book title -- a string of no more than 80 characters;
Line #3: the author -- a string of no more than 80 characters;
Line #4: the key words -- each word is a string of no more than 10 characters without any white space, and the keywords are separated by exactly one space;
Line #5: the publisher -- a string of no more than 80 characters;
Line #6: the published year -- a 4-digit number which is in the range [1000, 3000].
然后由m
个询问,询问的时候,根据上面的某个变量,查询出书的id
,排序输出。
询问格式为
1: a book title
2: name of an author
3: a key word
4: name of a publisher
5: a 4-digit number representing the year
解题思路
- 本题只需对每一个变量设置一个
map<string,vector<string>>
即可。 - 通过本题,应该学到
map
的使用 - 学会一些读入操作
getline,stringstream
如何读入一行,并且按照空格分割
string str,word;
getline(str);
stringstream line(str);
while(line>>word){
cout<<word<<endl;
}
#include<bits/stdc++.h>
using namespace std;
map<string,vector<string>>Title,Author,Keyword,Puplisher,Year;
int main(){
int n,m;
string tmp,keyword,id,author,title,publisher,year;
while(getline(cin,tmp)){
n=stoi(tmp);
for(int i=1;i<=n;++i){
getline(cin,id);
getline(cin,title);
Title[title].push_back(id);
getline(cin,author);
Author[author].push_back(id);
getline(cin,tmp);
stringstream line(tmp);
while(line>>keyword){
Keyword[keyword].push_back(id);
}
getline(cin,publisher);
Puplisher[publisher].push_back(id);
getline(cin,year);
Year[year].push_back(id);
}
getline(cin,tmp);
m=stoi(tmp);
while(m--){
string query;
getline(cin,query);
cout<<query<<endl;
int type=query[0]-'0';
query=query.substr(3);
switch (type){
case 1:
if(Title[query].size()==0){
cout<<"Not Found"<<endl;
break;
}
sort(Title[query].begin(),Title[query].end());
for(string s:Title[query]) cout<<s<<endl;
break;
case 2:
if(Author[query].size()==0){
cout<<"Not Found"<<endl;
break;
}
sort(Author[query].begin(),Author[query].end());
for(string s:Author[query]) cout<<s<<endl;
break;
case 3:
if(Keyword[query].size()==0){
cout<<"Not Found"<<endl;
break;
}
sort(Keyword[query].begin(),Keyword[query].end());
for(string s:Keyword[query]) cout<<s<<endl;
break;
case 4:
if(Puplisher[query].size()==0){
cout<<"Not Found"<<endl;
break;
}
sort(Puplisher[query].begin(),Puplisher[query].end());
for(string s:Puplisher[query]) cout<<s<<endl;
break;
case 5:
if(Year[query].size()==0){
cout<<"Not Found"<<endl;
break;
}
sort(Year[query].begin(),Year[query].end());
for(string s:Year[query]) cout<<s<<endl;
break;
}
}
}
return 0;
}