PAT真題

1012 The Best Rank (25 分)

此題難在結構體的設計,如何聯繫各個字段。=》此種類型多用結構體

#include <cstdio>
#include <algorithm>
using namespace std;
struct node {     // 使用結構體存儲
    int id, best;   // id記錄學號,best記錄最好的排列科目
    int score[4], rank[4];
}stu[2005];
int exist[1000000], flag = -1;
bool cmp1(node a, node b) {return a.score[flag] > b.score[flag];}   // 降序排列
int main() {
    int n, m, id;
    scanf("%d %d", &n, &m);    // 輸入學生個數n和詢問次數m
    for(int i = 0; i < n; i++) {
        // 依次錄入學號+3門成績
        scanf("%d %d %d %d", &stu[i].id, &stu[i].score[1], &stu[i].score[2], &stu[i].score[3]);
        stu[i].score[0] = (stu[i].score[1] + stu[i].score[2] + stu[i].score[3]) / 3.0 + 0.5;   // 平均分四捨五入
    }
    for(flag = 0; flag <= 3; flag++) {
        sort(stu, stu + n, cmp1);   // 分別按照每一項對結構體排序
        stu[0].rank[flag] = 1;      // 初始化排名第一名
        for(int i = 1; i < n; i++) {
            stu[i].rank[flag] = i + 1;  // 已經排序完成,則第i個同學排名爲第i名,形成並列的話 1 1 3 4
            if(stu[i].score[flag] == stu[i-1].score[flag])   // 分數一樣則排名一樣
                stu[i].rank[flag] = stu[i-1].rank[flag];
        }
    }
    for(int i = 0; i < n; i++) {
        exist[stu[i].id] = i + 1;   // 學號桶,學號---下標
        stu[i].best = 0;
        int minn = stu[i].rank[0];
        for(int j = 1; j <= 3; j++) {
            if(stu[i].rank[j] < minn) {  // 尋找排名最靠前的科目
                minn = stu[i].rank[j];
                stu[i].best = j;
            }
        }
    }
    char c[5] = {'A', 'C', 'M', 'E'};
    for(int i = 0; i < m; i++) {
        scanf("%d", &id);    // 輸入學號
        int temp = exist[id];   // 找到下標
        if(temp) {
            int best = stu[temp-1].best;
            printf("%d %c\n", stu[temp-1].rank[best], c[best]);
        } else {
            printf("N/A\n");
        }
    }
    return 0;
}

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