1047 Student List for Course (25 分)
题目大意
题目大意:给出选课人数和课程数目,然后再给出每个人的选课情况,请针对每门课程输出选课人数以及所有选该课的学生姓名,按照字典序。
基本思路
定义一个vector< string> v[2510];//下标是课程编号,值是选这门课的学生姓名。
- 将每个学生的选课信息装入容器vector< string>v[2050];
- 枚举i从1到m:输出每门课程的选课人数,对容器中的姓名(字符串)按字典序升序的排序,再输出这些姓名(字符串)
代码
#include <bits/stdc++.h>
using namespace std;
vector <string> v[2510];//下标是课程编号,值是选这门课的学生姓名
bool cmp(string a,string b){
return a<b;//按照字典序排序
}
int main(){
//读入
int n,m;//学生数量,课程数量
cin>>n>>m;
for(int i=0;i<n;i++){//遍历所有学生
string name;
cin>>name;
int k;//这个学生的选课数量
cin>>k;
for(int j=0;j<k;j++){
int id;
cin>>id;
v[id].push_back(name);
}
}
//枚举i从1到m:输出每门课程的选课人数,对容器中的姓名(字符串)按字典序升序的排序,再输出这些姓名(字符串)
for(int i=1;i<=m;i++){
cout<<i<<' '<<v[i].size()<<endl;
sort(v[i].begin(),v[i].end(),cmp);
for(int j=0;j<v[i].size();j++){
printf("%s\n",v[i][j].c_str());//直接用cout输出字符串会导致最后一个测试点超时,可以用str.c_str()输出以解决超时问题
}
}
}