[code] PTA 胡凡算法筆記 DAY019

題目A1025 PAT Ranking

在這裏插入圖片描述

  • 題意
    分別輸入N個考室的各考生成績,按總排名輸出,排名相同按編號從小到大輸出。輸出信息爲:registration_number final_rank location_number local_rank

  • 思路
    首先數據需要保存,所以按數據範圍申請數組,然後根據輸出格式可以確定結構體中的屬性是哪些。之後每個考室輸入完後需要先進行局部排序,去填local_rank。所有輸入完成之後,全局排序,填final_rank。也可以不填直接輸出。
    注意: 排名可以並列。

  • Code in C++

#include <iostream>
#include <algorithm>
#include <string>
#define maxn 30001

struct test_rank {
    std::string registration_number;
    int score;
    int final_rank;
    int location_number;
    int local_rank;
    void print() {
        std::cout << registration_number << " " << final_rank << " " << location_number << " " << local_rank << std::endl;
    }
} testees[maxn];

bool cmp(test_rank a, test_rank b) {
    if (a.score != b.score) return a.score > b.score;
    else return a.registration_number < b.registration_number;
}

void set_rank(int start, int end) {

    testees[start].local_rank = 1; // 排序後第一個排名一定是第一
    // 支持並列第一處理
    for (int i = 1; i <= end - start; ++i) {
        if (testees[start + i].score == testees[start + i -1].score) testees[start + i].local_rank = testees[start + i - 1].local_rank;
        else testees[start + i].local_rank = i + 1;
    }
}

int main()
{
    int n, k;
    int total = 0;
    std::cin >> n;
    for (int i = 1; i <= n; ++i) {
        std::cin >> k;
        for (int j = 0; j < k; ++j, ++total) {
            std::cin >> testees[total].registration_number >> testees[total].score;
            testees[total].location_number = i;
        }
        // 局部sort
        std::sort(testees + total - k, testees + total, cmp);
        // 設置local rank
        set_rank(total - k, total - 1);
    }

    // 全局sort
    std::sort(testees, testees + total, cmp);
    std::cout << total << std::endl;
    int r = 1; // 考生排名
    for (int i = 0; i < total; ++i) {
        if (i > 0 && (testees[i].score != testees[i -1].score)) {
            r = i + 1;
        }
        testees[i].final_rank = r;
        testees[i].print();
    }
    return 0;
}


小結

這裏沒認真看題目導致調試用了很長時間,並且在看到13位數字的時候我很自然的覺得用數值類型也可以保存編號字段,但是不知道爲什麼會出錯,就算換了long long,最後還是換成string之後才AC。

PS:感覺之後知識學的多點了,這個還可以擴展成分佈式同步做的code。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章