算法笔记练习 6.1 vector 问题 B: 【PAT 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.

输入
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.

输出
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.

样例输入

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

样例输出

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. stuName二维数组存储学生姓名,stuName[i]为第i名学生姓名的首地址;
  2. courseTablevector数组,存放每门课的选课情况,courseTable[i]是第i门课的选课情况,例如{1,3,4}就代表姓名为stuName[1]stuName[3]stuName[4]的学生选了这门课。

步骤:

  1. stuNamecourseTable接收所有数据;
  2. 遍历courseTable输出选课情况,对于每一门课,要先按照学生姓名的字典序对学生的编号进行排序,再输出排序后的姓名。

细节:

  • cmp函数里不能直接返回strcmp的结果,因为所有非零的值都会被转成true;
  • 输入中课程编号是 1~k 。

代码

#include 
#include 
#include 
#include 
using namespace std;

char stuName[40010][5];
vector<int> courseTable[2510];

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

int main() {
	int n, k;
	while (scanf("%d %d", &n, &k) != EOF) {
		memset(courseTable, 0, sizeof(courseTable));
		for (int stuNo = 0; stuNo != n; ++stuNo) {
			int courseCnt;
			scanf("%s %d", stuName[stuNo], &courseCnt);
			for (int i = 0; i != courseCnt; ++i) {
				int courseNo;
				scanf("%d", &courseNo);
				courseTable[courseNo-1].push_back(stuNo);
			} 
		}
		for (int i = 0; i != k; ++i) {
			printf("%d %d\n", i+1, courseTable[i].size());
			sort(courseTable[i].begin(), courseTable[i].end(), cmp); 
			for (auto it = courseTable[i].begin(); it != courseTable[i].end(); ++it)
				printf("%s\n", stuName[*it]);
		} 
	} 
	return 0;
} 

你可能感兴趣的:(算法笔记)