顺序扫描每名学生的分数与姓名,维护当前最高分及其姓名,只有严格更高分才替换,输出最后的姓名。
OJ: roj
题目 ID: 1147
难度:入门
标签:入门数组最值python
创建: 2026-09-29 20:49
更新: 2026-10-05 03:27
题目描述
输入学生人数 5 / 87 lilei / 99 hanmeimei / 97 lily / 96 lucy / 77 jim,输出 hanmeimei。
思路
顺序扫描每条记录,维护当前最高分与其姓名,只有分数严格大于当前最高分时才同时更新两者,因此并列时保留先到者,扫描结束后留下的姓名就是答案。分数非负,最高分初值取
参考代码
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;
}