一道技巧性很强的题,起先我尝试用数组来做,最后发现很困难,看了下算法笔记后采用map<string,set>成功通过
坑点如下
1,getline(cin,string)遇到换行结束,会读入空格,而cin>>key以空格或换行作为结束标识,因此在读入key的过程中尝试用getchar()读入空格。代码如下
while(cin>>key)
{
mpkey[key].insert(id);
c=getchar();
if(c=='\n')
{ break;}
}
2,注意map的用法
整体代码如下
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<string>
#include<iostream>
#include<map>
#include<set>
using namespace std;
const int maxn=10050;
const int maxq=1010;
struct node{
int id;
char title[85];
char author[85];
string key;
char pub[85];
char year[5];
}book[maxn];
map<string,set<int>>mptitle,mpauthor,mpkey,mppub,mpyear;
string title,author,key,pub,year;
void query(map<string,set<int>>&mp,string &str){
if(mp.find(str)==mp.end()) printf("Not Found\n");
else{
for(set<int>::iterator it=mp[str].begin();it!=mp[str].end();it++)
{
printf("%07d\n",*it);
}
}
}
int main(){
int n;
scanf("%d",&n);
int id;
char c;
for(int i=0;i<n;i++){
scanf("%d",&id);
getchar();
getline(cin,title);
mptitle[title].insert(id);
getline(cin,author);
mpauthor[author].insert(id);
while(cin>>key)
{
mpkey[key].insert(id);
c=getchar();
if(c=='\n')
{ break;}
}
getline(cin,pub);
mppub[pub].insert(id);
getline(cin,year);
mpyear[year].insert(id);
}
int m;
scanf("%d",&m);
string words;
int num;
for(int i=0;i<m;i++)
{
scanf("%d: ",&num);
getline(cin,words);
printf("%d: %s\n",num,words.c_str());
if(num==1) query(mptitle,words);
else if(num==2) query(mpauthor,words);
else if(num==3) query(mpkey,words);
else if(num==4) query(mppub,words);
else query(mpyear,words);
}
return 0;
}