(PAT)1047 Student List for Course (哈希的应用)

落日映苍穹つ 2022-05-10 00:14 226阅读 0赞

Zhejiang University has 40,000 students and provides 2,500 courses. Now given the registered course list of each student, you are supposed to output the student name lists of all the courses.

Input Specification:

Each input file contains one test case. For each case, the first line contains 2 numbers: N (≤40,000), the total number of students, and K (≤2,500), the total number of courses. Then N lines follow, each contains a student’s name (3 capital English letters plus a one-digit number), a positive number C (≤20) which is the number of courses that this student has registered, and then followed by C course numbers. For the sake of simplicity, the courses are numbered from 1 to K.

Output Specification:

For each test case, print the student name lists of all the courses in increasing order of the course numbers. For each course, first print in one line the course number and the number of registered students, separated by a space. Then output the students’ names in alphabetical order. Each name occupies a line.

Sample Input:

  1. 10 5
  2. ZOE1 2 4 5
  3. ANN0 3 5 2 1
  4. BOB5 5 3 4 2 1 5
  5. JOE4 1 2
  6. JAY9 4 1 2 5 4
  7. FRA8 3 4 2 5
  8. DON2 2 4 5
  9. AMY7 1 5
  10. KAT3 3 5 4 2
  11. LOR6 4 2 4 1 5

解题思路:

  1. const int maxn = 40010; //学生数量
  2. const int maxc = 2510; //课程数量
  3. char name[maxn][5]; //学生表
  4. vector<int> course[maxc]; //存放第i门课所有学生编号

我们可以构建两个表,第一个表用来存储学生的姓名,maxn数组后缀可以用来作为学生的ID

第二个表是课程表,用来存储各课程所报名参加的学生(存储在vector中) maxn数组后缀可以用来作为课程ID

我们可以把输入的学生用先定义一个标识,并把这个标识作为数组索引来存储学生名

然后再把这个标识放到对应的课程容器中去

  1. int i = 0;
  2. for (; i < n; ++i) {
  3. int scours;
  4. scanf("%s %d", name[i], &scours);
  5. for (int j = 0; j < scours; ++j) {
  6. int cno;
  7. scanf("%d",&cno);
  8. course[cno].push_back(i); //存放第i门课所有学生编号
  9. }
  10. }

输出时,我们按顺序输出课程号和报名学生的数量

然后根据题意按照字典序输出学生名

这里先要对学生名排序,我们可以写一个元函数

  1. bool cmp(int a, int b) {
  2. return strcmp(name[a], name[b]) < 0; //名字按照字典序排序
  3. }

然后进行排序

  1. sort(course[i].begin(), course[i].end(), cmp);

然后输出就可以了

  1. for (int i = 1; i <= k; ++i) {
  2. printf("%d %d\n", i, course[i].size());
  3. sort(course[i].begin(), course[i].end(), cmp); //按照字典序排序
  4. for (int j = 0; j < course[i].size(); ++j) {
  5. printf("%s\n", name[course[i][j]]);
  6. }
  7. }

发表评论

表情:
评论列表 (有 0 条评论,226人围观)

还没有评论,来说两句吧...

相关阅读

    相关 应用

      一 哈希介绍 1、若关键字为k,则其值存放在f(k)的存储位置上。由此,不需比较便可直接取得所查记录。称这个对应关系f为散列函数,按这个思想建立的表为散列表。 2、对