pat 1047 解题心得

1047. Student List for Course (25)

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.

题目要求简单描述为:有N名同学和K门课程,然后根据每位同学选课的情况,统计出每门课程的选课同学并输出,输出要求为【课程号 选课人数 所有人的名字】,其中课程号要按照顺序,学生名字也要按照字典顺序输出

初看这道题目,如果做过1039的朋友就会立即联想到,两道题目的共同问题都是在于数据量与执行效率的问题,最大的test case都是4万*2500,由于涉及到一对多的数据存储,我们很容易想到的是用STL,但是存在问题就是STL在大数据量的时候时间问题是一个很必须要考虑的因素,就像这里直接用名字作为对象进行存储或排序都会让时间超过

      这里的解法是结合vector+sort+字符串向整型转换,最终最大的case消耗的时间超过了最大的一半,内存也耗了将近最大的四分之一

以下是代码部分,供大家一起参考学习讨论

 1 #include <stdio.h>
 2 #include <algorithm>
 3 #include <vector>
 4 #include <string.h>
 5 using namespace std;
 6 vector<int> course[2510];
 7 char nameIndex[180000][5];
 8 int convert(char a[]);
 9 bool cmp(int a, int b){
10     return a<b;
11 }
12 int main(){
13     char name[5];
14     int N, K, C, i, j,cId,nameId;
15     string temp;
16     vector<int>::iterator vI;
17     scanf("%d %d", &N, &K);
18     for (i = 0; i < N; i++){
19         scanf("%s %d", name,&C);
20         nameId = convert(name);
21         strcpy(nameIndex[nameId], name);
22         for (j = 0;j < C; j++){
23             scanf("%d", &cId);
24             course[cId].push_back(nameId);
25         }
26 
27     }
28     for (i = 1; i <= K; i++){
29         printf("%d %d
", i, course[i].size());
30         sort(course[i].begin(), course[i].end(), cmp);
31         for (vI = course[i].begin(); vI != course[i].end(); vI++)
32             printf("%s
", nameIndex[*vI]);
33     }
34     system("pause");
35     return 0;
36 }
37 int convert(char a[]){
38     int result = 0, i;
39     for (i = 0; i <3; i++)
40         result = result * 26 + a[i] - 'A';
41     result = result * 10 + a[3] - '0';
42     return result;
43 }
原文地址:https://www.cnblogs.com/KarayLee/p/karayLee_1047PAT.html