题目链接
注意点:
1.用map处理姓名会超时,只能用散列方式。
2.由于数据量很大,不能用二维数组的方式,需要用vector来减少空间消耗。
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
const int M=26*26*26*26;//由姓名散列组成的数字上界
vector<int> selectCourese[M];//每个学生选择的课程编号
int change(char name[]){//散列函数,将姓名字符串转换为数字
int res=0;
for(int i=0;i<3;i++){
res+=name[i]-'A';
res*=26;
}
res+=name[3]-'0';
return res;
}
int main(){
int n,k,regisnum,index;
char temname[10];
scanf("%d%d",&n,&k);//人数及课程数
for(int i=0;i<k;i++){//对每门课程
scanf("%d%d",&index,®isnum);//输入课程编号和选课人数
for(int j=0;j<regisnum;j++){
scanf("%s",temname);//输入选课学生姓名
selectCourese[change(temname)].push_back(index);
//将课程编号加入到该生的选课数组中
}
}
for(int i=0;i<n;i++){//对每一查询
scanf("%s",temname);//输入姓名
printf("%s %d",temname,selectCourese[change(temname)].size());
//输出姓名,选课数
sort(selectCourese[change(temname)].begin(),selectCourese[change(temname)].end());//从小到大排列
for(vector<int>::iterator it=selectCourese[change(temname)].begin();it!=selectCourese[change(temname)].end();it++){
printf(" %d",*it);//输出选课编号
}
printf("\n");
}
return 0;
}