成绩排序

GitHub跳转原题关系图返回列表

把学生按成绩降序排序,同分时按姓名字典序升序输出。

OJ: roj

题目 ID: 1178

难度:入门

标签:排序

创建: 2026-09-29 22:16

更新: 2026-10-05 04:26

题目描述

给出班里 nn(0<n<200<n<20)个学生的姓名与成绩,成绩为 [0,100][0,100] 的整数,按成绩从高到低输出,同分时姓名字典序小的在前,每行 名字 成绩。样例:输入 4 / Kitty 80 / Hanmeimei 90 / Joey 92 / Tim 28,输出 Joey 92 / Hanmeimei 90 / Kitty 80 / Tim 28。

思路

存 (name, score),自定义比较:成绩降序,同分则名字字典序升序,sort 一遍后按序输出。

参考代码

Python 版:

python
#!/usr/bin/env python3
# Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
# rbook: -> https://rbook.roj.ac.cn  https://rbook2.roj.ac.cn
# rainboy的学习导航网站: https://idx.roj.ac.cn
# create_at: 2026-05-22 19:17
# update_at: 2026-10-04 10:19

import sys


def solve() -> None:
    data = iter(map(lambda b: b.decode(), sys.stdin.buffer.read().split()))
    n = int(next(data))  # 题面的 n:接下来有 n 行「姓名 成绩」
    students: list[tuple[str, int]] = [
        (next(data), int(next(data))) for _ in range(n)
    ]
    # 成绩降序,同分名字字典序升序
    students.sort(key=lambda x: (-x[1], x[0]))
    print('\n'.join(f"{name} {score}" for name, score in students))


if __name__ == "__main__":
    solve()

C++ 版(同一算法):

cpp
/**
 * Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
 * rbook: -> https://rbook.roj.ac.cn  https://rbook2.roj.ac.cn
 * rainboy的学习导航网站: https://idx.roj.ac.cn
 * create_at: 2026-10-05 04:26
 * update_at: 2026-10-05 04:26
 */
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;

typedef long long ll;

// n < 20,开 25 足够。
const ll MAXN = 25;

// stu[i] = 第 i 个学生的 (名字, 成绩)
string stu_name[MAXN];
ll stu_score[MAXN];

ll n;
// order[i] = 按规则排好后第 i 名的原始下标(用下标排序避免搬动 string)。
ll order[MAXN];

// 比较规则:成绩降序;成绩相同则名字字典序升序。
bool cmp_by_score_name(ll i, ll j) {
    if (stu_score[i] != stu_score[j]) return stu_score[i] > stu_score[j];
    return stu_name[i] < stu_name[j];
}

void read_input() {
    cin >> n;
    for (ll i = 1; i <= n; i++) {
        cin >> stu_name[i] >> stu_score[i];
        order[i] = i;
    }
}

void solve() {
    // 用下标数组排序,避免交换 string。
    sort(order + 1, order + n + 1, cmp_by_score_name);
    for (ll k = 1; k <= n; k++) {
        ll i = order[k];
        cout << stu_name[i] << " " << stu_score[i];
        if (k != n) cout << "\n";
    }
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    read_input();
    solve();

    return 0;
}