这道题如果用 map<string, vector< int> >,对最后一个数据,十有八九会超时,但是如果用unordered_map<string, vector< int > >的话,最后一个数据在大多数情况下,能通过(不过也是在危险边缘了,时间限制是600ms, 用 unordered_map的话,大概在350-550 ms 之间),话不多说,如下:
#include <cstdio>
#include <iostream>
#include <string>
#include <algorithm>
#include <unordered_map>
#include <vector>
using namespace std;
unordered_map<string, vector<int> > stu;
int main(){
int n, k;
scanf("%d %d",&n,&k);
for (int i=1; i<=k; i++){
int num,index;
scanf("%d %d",&index, &num);
for (int j=0; j<num; j++){
string name;
cin>>name;
stu[name].push_back(index);
}
}
for (int i=0; i<n; i++){
string name;
cin>>name;
cout<<name;
printf(" %d",stu[name].size());
sort(stu[name].begin(),stu[name].end());
for (int j=0; j<stu[name].size(); j++){
printf(" %d",stu[name][j]);
}
printf("\n");
}
}
这题也可以用map<string, string >来写,不过最后一个数据肯定会超时。至于到底是哪个部分耗时那么长,个人认为是输入输出部分,也就是cin, cout, 归根结底还是因为string 的存在,导致不得不用cin/cout, 而map 的自动排序,其实并没有耗费多长时间,当然相对于unordered_map来说,map的用时明显长一些.
另外,unordered_map是C++11的标准,所以在DEVC中编译的时候,要加入-std=c++ 11命令, 不过PAT的评测系统(至少)已经是11标准了,写unordered_map完全能接受。