PAT 1047

题目

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.

给出每个同学选的课程,要求输出每个课程的同学名字,按字典序输出

代码和思路

  1. 主要问题出在按照字典序输出,如果用string读入,然后再使用hash,取出所有课程的学生后在进行排序,会超时。
  2. cmp函数,可以让一个数组按照一定的内部规律排序,所以可以写以下代码,让他们按照所对应的字典序排序
    bool cmp(int a, int b) {
    	return strcmp(name[a], name[b]) < 0;
    }
    
  3. 然后就是读入的问题,如上所述,用string可能会超时,所以使用char数组读入(用vs读char字符串真的。。。很容易报错。。一模一样的代码放dev就没事。。)
  4. 读入后按照内部规律排序输出即可,处理好输入和排字典序问题是这个题的关键
    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    #include<vector>
    using namespace std;
    const int maxn = 40010;
    const int maxc = 2510;
    
    char name[maxn][5];
    vector<int> course[maxc];
    
    bool cmp(int a, int b) {
    	return strcmp(name[a], name[b]) < 0;
    }
    
    int main() {
    	int n, k;
    	int c, courseId;
    	scanf("%d %d", &n, &k);
    	for (int i = 0; i < n; i++) {
    		scanf("%s", name[i]);
    		scanf("%d", &c);
    		for (int j = 0; j < c; j++) {
    			scanf("%d", &courseId);
    			course[courseId].push_back(i);
    		}
    	}
    	for (int i = 1; i <= k; i++) {
    		printf("%d %d\n", i, course[i].size());
    		sort(course[i].begin(), course[i].end(), cmp);
    		for (int j = 0; j < course[i].size(); j++) {
    			printf("%s\n", name[course[i][j]]);
    		}
    	}
    	return 0;
    }
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值