【題解】ZeroJudge b158: NOIP2007 1.奖学金

【題目敘述】https://zerojudge.tw/ShowProblem?problemid=b158
【解題想法】排序

#include <iostream>
#include <algorithm>
using namespace std;
//先按总分从高到低排序
//如果两个同学总分相同,再按语文成绩从高到低排序
//如果两个同学总分和语文成绩都相同,那么规定学号小的同学排在前面

struct Score{
    //学号、语文、数学、英语、总分
    int id, n1, n2, n3, total;
};

bool cmp(Score a, Score b){
    if (a.total == b.total){
        if (a.n1 == b.n1){
            return a.id < b.id;
        }else return a.n1 > b.n1;
    }else return a.total > b.total;
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    int n, x, y, z;
    while (cin >> n){
        Score stu[n];
        for (int i=0; i<n; i++){
            cin >> x >> y >> z;
            stu[i] = {i+1, x, y, z, x+y+z};
        }
        sort(stu, stu+n, cmp);
        for (int i=0; i<5; i++){
            cout << stu[i].id << ' ' << stu[i].total << '\n';
        }
    }
    return 0;
}

Python code (credit: Amy Chou)

while True:
    try:
        n = int(input())
        student = []
        for idx in range(1, n+1):
            lst = [idx]
            lst.extend(list(map(int, input().split())))
            lst.append(lst[-1]+lst[-2]+lst[-3])
            student.append(lst)
        student.sort(key=lambda x: (-x[4], -x[1], x[0]))
        for i in range(5):
            print(student[i][0], student[i][4])
        #print()
    except:
        break
分享本文 Share with friends