#include <iostream>
#include <string.h>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
int n,k,c,temp;
cin>>n>>k;
vector<vector<string>> course(k+1);
string name;
for(int i=0;i<n;++i){
cin>>name>>c;
for(int j=0;j<c;++j){
cin>>temp;
course[temp].push_back(name);
}
}
for(int i=1;i<=k;++i){
int size=course[i].size();
cout<<i<<" "<<size<<endl;
sort(course[i].begin(),course[i].end());
for(int j=0;j<size;++j)
cout<<course[i][j]<<endl;
}
return 0;
}
内存优化后还是超时
#include <iostream>
#include <algorithm>
#include <vector>
#include <unordered_map>
using namespace std;
vector<string>dict;
bool cmp1(int a,int b){
return dict[a]<dict[b];
}
int main() {
int n,k,c,cnt=0,temp;
unordered_map<string,int>mapp;
cin>>n>>k;
string name;
vector<vector<int>> course(k+1);
dict.push_back(" ");
for(int i=0;i<n;++i){
cin>>name>>c;
if(mapp[name]==0) {
mapp[name]=++cnt;
dict.push_back(name);
}
for(int j=0;j<c;++j){
cin>>temp;
course[temp].push_back(cnt);
}
}
for(int i=1;i<=k;++i){
int size=course[i].size();
cout<<i<<" "<<size<<endl;
sort(course[i].begin(),course[i].end(),cmp1);
for(int j=0;j<size;++j)
cout<<dict[course[i][j]]<<endl;
}
return 0;
}
AC代码
#include <iostream>
#include <vector>
#include <algorithm>
#include <string.h>
using namespace std;
char name[40010][5];
vector<int> course[2510];
bool cmp1(int a, int b) {
return strcmp(name[a], name[b]) < 0;
}
int main() {
int n, k;
scanf("%d %d", &n, &k);
for(int i = 0; i < n; i++) {
int cnt, temp;
scanf("%s %d", name[i], &cnt);
for(int j = 0; j < cnt; j++) {
scanf("%d", &temp);
course[temp].push_back(i);
}
}
for(int i = 1; i <= k; i++) {
printf("%d %d\n", i, course[i].size());
sort(course[i].begin(), course[i].end(), cmp1);
for(int j = 0; j < course[i].size(); j++)
printf("%s\n", name[course[i][j]]);
}
return 0;
}