PAT-A1047. Student List for Course【排序】

思路:
1、set(string)数组,以课程号为下标,最后一组超时
//set内部对string排序,不用set,要自己排序,但由于可以用char[],更快
2、可以发现,string排序会超时,用char[] + vector 呗
输出时,在每个课程内部先排序
排序时,用下标排序,而不是字符串本身

小技巧:
如果排序是直接对字符串排序,那么会导致大量的字符串移动,非常消耗时间。因此比较合适的做法是使用 字符串的下标 来代替字符串本身进行排序

/**************************
//@Author: 3stone
//@ACM: PAT-A1047
//@Time: 18/1/27
//@IDE: VS2017
***************************/
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<vector>
#define maxSize 40010
using namespace std;

char name[maxSize][5];
vector<int> cour[2510];

bool cmp(int s1, int s2) {
    return strcmp(name[s1], name[s2]) < 0;
}

int main() {
    int stuNum, subNum;
    scanf("%d%d", &stuNum, &subNum);

    for (int i = 1; i <= stuNum; i++) {//获取选课信息
        int total, sub;  //选课人数 & 课程编号
        scanf("%s%d", name[i], &total);
        for (int j = 0; j < total; j++) {
            scanf("%d", &sub); 
            cour[sub].push_back(i); //学生编号放入课程记录中
        }
    }

    for (int i = 1; i <= subNum; i++) { //output
        sort(cour[i].begin(), cour[i].end(), cmp);
        int count = cour[i].size();
        printf("%d %d\n", i, count);

        if (count == 0) continue;
        else {
            vector<int>::iterator tempEnd = cour[i].end();
            for (vector<int>::iterator it = cour[i].begin(); it != tempEnd; it++) {
                printf("%s\n", name[(*it)]);
            }
        }
    }

    system("pause");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_26398495/article/details/79184395