水题,当作是熟练MAP吧。
map <string, std::vector<int> > mp[N]
key
: string,各种关键词
value
: int,书的序号,这里比较特殊,一个key
可以有多个value
string book[M]
:将书序号和真正的序列号对应起来,注意书序列号排序后输出。
貌似也可以一开始就建立一个map<string, std::vector<string> >
,序列号作为里面的value。建立以后直接排序。
存下模板,以后备用。
/*-------------------------------------------- * File Name: PAT 1022. Digital Library * Author: Danliwoo * Mail: [email protected] * Created Time: 2016-05-23 16:01:39 --------------------------------------------*/
#include <bits/stdc++.h>
using namespace std;
#define N 6
#define M 10010
map <string, std::vector<int> > mp[N];
map <string, std::vector<int> >::iterator iter;
string line[N], book[M], str, ans[M];
int main()
{
int n, m;
while(~scanf("%d", &n)){
getchar();
for(int k = 1;k <= n;k++){
for(int i = 0;i < N;i++){
getline(cin, line[i]);
if(i == 3){
istringstream sm(line[i]);
while(sm >> str)
mp[i][str].push_back(k);
} else{
if(i == 0) book[k] = line[i];
mp[i][line[i]].push_back(k);
}
}
}
scanf("%d", &m);
while(m--){
int id;
scanf("%d: ", &id);
printf("%d: ", id);
getline(cin, str);
cout << str << endl;
iter = mp[id].find(str);
if(iter != mp[id].end()){
std::vector <int> q = mp[id][str];
for(int i = 0;i < q.size();i++)
ans[i] = book[q[i]];
sort(ans, ans+q.size());
for(int i = 0;i < q.size();i++)
cout << ans[i] << endl;
} else cout << "Not Found\n";
}
}
return 0;
}
若要对vector里的量排序则:
map <string, std::vector<int> >::iterator iter;
for(iter = mp.begin();iter != mp.end();iter++)
sort(iter->second.begin(), iter->second.end());