PAT A1025 PAT Ranking(sort部分排名)

sunlanchang發表於2019-02-01

Description

有n個考場,每個考場若干學生,給出給個考場每個雪神的准考證號和成績,按成績排名,成績相同按照準考證好遞增排序。

Output

輸出考生總數,和考生的准考證號,總排名,考場號,考場內排名。

Sample Input:

2
5
1234567890001 95
1234567890005 100
1234567890003 95
1234567890002 77
1234567890004 85
4
1234567890013 65
1234567890011 25
1234567890014 100
1234567890012 85

Sample Output:

9
1234567890005 1 1 1
1234567890014 1 2 1
1234567890001 3 1 2
1234567890003 3 1 2
1234567890004 5 1 4
1234567890012 5 2 2
1234567890002 7 1 5
1234567890013 8 2 3
1234567890011 9 2 4

Solution

sort靈活運用。相當於對陣列內部分排序,後對整個陣列排序即可。

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
using namespace std;
struct Student
{
    char reg_num[15];
    int final_rank, location_num, local_rank, grade;
    bool operator<(const Student &t) const
    {
        if (t.grade != grade)
            // 成績遞減
            return grade > t.grade;
        // 學號遞增
        return strcmp(reg_num, t.reg_num) < 0;
    }
};
Student stu[33333];
int main()
{
   // freopen("in.txt", "r", stdin);
    int Case, total_num = 0;
    scanf("%d", &Case);
    for (int loc_num = 1; loc_num <= Case; loc_num++)
    {
        int K;
        scanf("%d", &K);
        for (int line = 1; line <= K; line++)
        {
            scanf("%s %d", &stu[total_num].reg_num, &stu[total_num].grade);
            stu[total_num].location_num = loc_num;
            total_num++;
        }
        //部分排名
        int start = total_num - K;
        sort(stu + start, stu + total_num);
        int tmp_rank = 1;
        stu[start].local_rank = 1;
        for (int i = start + 1; i < total_num; i++)
        {
            tmp_rank++;
            if (stu[i].grade != stu[i - 1].grade)
                stu[i].local_rank = tmp_rank;
            else
                stu[i].local_rank = stu[i - 1].local_rank;
        }
    }
    // 總體排名
    sort(stu, stu + total_num);
    int tmp_rank = 1;
    stu[0].final_rank = 1;
    for (int i = 1; i < total_num; i++)
    {
        tmp_rank++;
        if (stu[i].grade != stu[i - 1].grade)
            stu[i].final_rank = tmp_rank;
        else
            stu[i].final_rank = stu[i - 1].final_rank;
    }
    printf("%d\n", total_num);
    for (int i = 0; i < total_num; i++)
    {
        printf("%s %d %d %d\n", stu[i].reg_num, stu[i].final_rank, stu[i].location_num, stu[i].local_rank);
    }
    return 0;
}