1047 Student List for Course (25 分)

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:

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

满分代码:

#include "cstdio"

#include "cstring"

#include "algorithm"

#include "vector"

using namespace std;

bool compare(char* a,char* b){

    return strcmp(a, b)<0;

}

int main(){

    int number,courseNumber;

    int totalCourse;

    scanf("%d %d",&number,&courseNumber);

    char name[number][5];       //注意 不能只用一个name,因为name为指针,如果复用name会让所有的值都为name最后指向的值,所以开辟了一个人数大小的name指针数组

    vector<char*> course[courseNumber];     //定义一个char*向量类型的数组

    for (int i=0; i<number; i++) {

        scanf("%s %d",name[i],&totalCourse);

        for (int j=0; j<totalCourse; j++) {

            int current;

            scanf("%d",&current);

            course[current-1].push_back(name[i]);   //将name压入对应的课程

        }

    }

    for (int i=0; i<courseNumber; i++) {

        printf("%d %lu\n",i+1,course[i].size());

        sort(course[i].begin(), course[i].end(),compare);   //字母序排序

        for (vector<char*>::iterator it=course[i].begin(); it!=course[i].end(); it++) {

            printf("%s",*it);

            if (it!=course[i].end()-1||i!=courseNumber-1) {

                printf("\n");

            }

        }

            }}

反思:

这里算法笔记里的思路和代码结构大致与我相近,不过最主要的一个区别(算法笔记的较好)是将vector定义为一个int类向量,而为定义的是一个char*类的向量,不过这样的话他怎么来存储名字呢,原来仔细思考可以发现名字在name数组中已经是按输入顺序排好了,只需要将第i个姓名的i存入数组就行,最后输出的时候根据i去找name[i]即可 

发布了14 篇原创文章 · 获赞 0 · 访问量 145

猜你喜欢

转载自blog.csdn.net/Yanhaoming1999/article/details/102726624