PTA 7-47 打印选课学生名单

本题考点:

  • 排序的应用

假设全校有最多40000名学生和最多2500门课程。现给出每个学生的选课清单,要求输出每门课的选课学生名单。
输入格式:
输入的第一行是两个正整数:N(≤40000),为全校学生总数;K(≤2500),为总课程数。此后N行,每行包括一个学生姓名(3个大写英文字母+1位数字)、一个正整数C(≤20)代表该生所选的课程门数、随后是C个课程编号。简单起见,课程从1到K编号。

这道题直接用 vector 存储即可,但是注意,当数据量很大的时候,cin,cout 用来输入输出就不合适了,这个时候应该选择 scanf,printf 来处理输入输出(真是超时解决的一个方法…)。

完整代码实现如下:


#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#define LOCAL
using namespace std;

#define MAXN 2510

vector<string> lists[MAXN];

int main()
{
#ifdef LOCAL
    freopen("data.txt", "r", stdin);
#endif
    int N, K;
    scanf("%d%d", &N, &K);
    getchar();
    string name;
    char nameChar[5];
    int cnt, classId;
    for (int i = 0; i < N; i++)
    {
        scanf("%s", nameChar);
        name = string(nameChar);
        scanf("%d", &cnt);
        while (cnt--)
        {
            scanf("%d", &classId);
            lists[classId].push_back(name);
        }
        getchar();
    }
    int len;
    for (int i = 1; i <= K; i++)
    {
        sort(lists[i].begin(), lists[i].end());
        printf("%d %d
", i, lists[i].size());
        for (int j = 0; j < lists[i].size(); j++)
        {   // 字符串转为 字符串数组
            len = lists[i][j].copy(nameChar, lists[i][j].size());
            printf("%s
", nameChar);
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/veeupup/p/12684171.html