最高分数的学生姓名

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

顺序扫描每名学生的分数与姓名,维护当前最高分及其姓名,只有严格更高分才替换,输出最后的姓名。

OJ: roj

题目 ID: 1147

难度:入门

标签:入门数组最值python

创建: 2026-09-29 20:49

更新: 2026-10-05 03:27

题目描述

输入学生人数 NN(N≤100N \le 100),再输入 NN 行,每行是「分数 姓名」:分数为不超过 100100 的非负整数,姓名不含空格且长度不超过 2020。要求输出分数最高者的姓名,数据保证最高分只有一位。样例输入 5 / 87 lilei / 99 hanmeimei / 97 lily / 96 lucy / 77 jim,输出 hanmeimei。

思路

顺序扫描每条记录,维护当前最高分与其姓名,只有分数严格大于当前最高分时才同时更新两者,因此并列时保留先到者,扫描结束后留下的姓名就是答案。分数非负,最高分初值取 −1-1 即可省掉第一位学生的特判;全程只扫一遍,时间复杂度 O(N)O(N)。

参考代码

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-09-28 18:00
# update_at: 2026-10-04 10:27

import sys


def solve() -> None:
    """读取学生人数、分数与姓名,输出最高分的姓名。"""
    data = iter(sys.stdin.buffer.read().split())
    n = int(next(data))
    best_score = -1
    best_name = ""
    # 每两项为一组:分数、姓名,next() 顺序消费一对。
    for _ in range(n):
        score = int(next(data))
        name = next(data).decode()
        if score > best_score:
            best_score = score
            best_name = name
    print(best_name)


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 03:27
 * update_at: 2026-10-05 03:27
 */
#include <iostream>
#include <string>
using namespace std;

typedef long long ll;

ll n;
ll best_score;    // 当前见过的最高分
string best_name; // 当前最高分对应的姓名

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

    cin >> n;
    best_score = -1; // 分数非负,第一位学生一定被接收
    for (ll i = 1; i <= n; i++) {
        ll score;
        string name;
        cin >> score >> name;
        // 只有严格更高才换人,并列时保留先到者
        if (score > best_score) {
            best_score = score;
            best_name = name;
        }
    }
    cout << best_name << "\n";
    return 0;
}