A1047. Student List for Course

Zhejiang University has 40000 students and provides 2500 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 (<=40000), the total number of students, and K (<=2500), 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:

10 5
ZOE1 2 4 5
ANN0 3 5 2 1
BOB5 5 3 4 2 1 5
JOE4 1 2
JAY9 4 1 2 5 4
FRA8 3 4 2 5
DON2 2 4 5
AMY7 1 5
KAT3 3 5 4 2
LOR6 4 2 4 1 5

Sample Output:

1 4
ANN0
BOB5
JAY9
LOR6
2 7
ANN0
BOB5
FRA8
JAY9
JOE4
KAT3
LOR6
3 1
BOB5
4 7
BOB5
DON2
FRA8
JAY9
KAT3
LOR6
ZOE1
5 9
AMY7
ANN0
BOB5
DON2
FRA8
JAY9
KAT3
LOR6
ZOE1

 1 #include<cstdio>
 2 #include<iostream>
 3 #include<algorithm>
 4 #include<vector>
 5 #include<string.h>
 6 using namespace std;
 7 char name[40001][5];
 8 vector<int> course[2501];
 9 bool cmp(int a, int b){
10     return strcmp(name[a], name[b]) < 0;
11 }
12 int main(){
13     int N, K, Ni;
14     scanf("%d%d", &N, &K);
15     for(int i = 0; i < N; i++){
16         scanf("%s", name[i]);
17         scanf("%d", &Ni);
18         for(int j = 0; j < Ni; j++){
19             int cId;
20             scanf("%d", &cId);
21             course[cId].push_back(i);
22         }
23     }
24     for(int i = 1; i <= K; i++){
25         int len = course[i].size();
26         printf("%d %d
", i, len);
27         sort(course[i].begin(), course[i].end(), cmp);
28         for(int j = 0; j < len; j++){
29             printf("%s
", name[course[i][j]]);
30         }
31     }
32     cin >> N;
33     return 0;
34 }
View Code

总结:

1、在开二维数组占用空间过大的情况下,可以使用vector<int> num[N],由于初始时每一个vector内均无元素,所以数组可以开的很大。

2、本题需要以课程为主体,存储选课的学生,如果对于每一门课都存储选课的学生名字的话,需要使用string存在vector数组中,需要char[] 与string的互转,比较浪费时间。可以直接把名字作为data存储下来,在vector数组中仅仅存储data的下标即可。 在名字字典序排序时可以用如下方法,用字符串下标代替字符串进行排序

bool cmp(int a, int b){
  return strcmp(name[a], name[b]) < 0;
}

3、sort对vector排序时,区间应填入:sort(vec.begin(), vec.end(), cmp);