PAT-甲级-1025 PAT Ranking

考察结构体的排序
比较有趣的点是local_rank的获取,输入每个考场的学生之后就排序,得到local_rank;所有输入完毕后排序得到final_rank.

//#define _CRT_SECURE_NO_WARNINGS
#include
using namespace std;
struct Student
{
     
    string registration_number;
    int scores{
      -1 };
    int location_number{
     0};
    int local_rank{
      0 };
    int final_rank{
      0 };
};
Student testee[30010];
bool cmp(Student &a, Student &b) {
      //先按照分数降序,再按照注册号升序
    if (a.scores != b.scores) return a.scores > b.scores;
    else return a.registration_number < b.registration_number;
}
int main()
{
     
    //freopen("input.txt", "r", stdin); 
    int N; cin >> N;
    int ctr = 0; 
    for (int local_ctr = 1; local_ctr <= N; ++local_ctr) {
      //local_ctr 考场号计数
        int K; cin >> K;
        for (int i = 0; i < K; ++i) {
      //每个考场K个人
            cin >> testee[ctr].registration_number >> testee[ctr].scores;
            testee[ctr].location_number = local_ctr;
            ++ctr;
        }
        sort(testee + ctr - K, testee + ctr, cmp);//对每个考场里的K个人排序,写入local_rank
        for (int i = ctr - K; i < ctr; ++i) {
     
            if (i == ctr - K) {
      testee[i].local_rank = 1; continue; }
            if (testee[i].scores == testee[i - 1].scores) {
     
                testee[i].local_rank = testee[i - 1].local_rank;
            }
            else {
     
                testee[i].local_rank = i - (ctr - K) + 1;
            }
        }
    }
    sort(testee, testee + ctr, cmp); //对所有人总排序,写入final_rank;
    for (int i = 0; i < ctr; ++i) {
     
        if (i == 0) testee[i].final_rank = 1;
        if (testee[i].scores == testee[i - 1].scores) {
     
            testee[i].final_rank = testee[i - 1].final_rank;
        }
        else {
     
            testee[i].final_rank = i + 1;
        }
    }
    cout << ctr << endl; //输出
    for (int i = 0; i < ctr; ++i) {
     
        cout << testee[i].registration_number << " " << testee[i].final_rank
            << " " << testee[i].location_number << " " << testee[i].local_rank << endl;
    }
    return 0;
}

你可能感兴趣的:(排序算法)