用元组保存学生记录,顺序扫描并维护总分最高且最先出现的学生。
OJ: luogu
题目 ID: P5740
难度:入门
标签:模拟结构体python
日期: 2026-07-15 21:15
题意
给出若干名学生的姓名和三科成绩。输出总分最高的学生信息;如果总分相同,输出输入中靠前的那位。
思路
Python 里可以用元组保存一名学生:
python
(name, chinese, math, english)顺序读入每名学生,计算三科总分。只有当当前学生总分严格大于 best_total 时,才更新答案。这样如果总分相同,就会自然保留先出现的学生。
这题是记录数据和维护最大值练习,不创建 brute.py。
Python 知识
/home/rainboy/mycode/hugo-blog/content/program_language/python/input_output_and_strings.md:一行中混合字符串和整数时,先split()再分别转换。/home/rainboy/mycode/hugo-blog/content/program_language/python/collections_toolkit.md:元组适合保存固定结构的一条记录。best_student = (name, chinese, math, english)保存当前最优记录。- 只在
total > best_total时更新,保留并列时靠前者。
代码
python
n = int(input())
best_student = None
best_total = -1
for _ in range(n):
name, chinese, math, english = input().split()
chinese = int(chinese)
math = int(math)
english = int(english)
total = chinese + math + english
if total > best_total:
best_total = total
best_student = (name, chinese, math, english)
print(best_student[0], best_student[1], best_student[2], best_student[3])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-07-27 00:00
* update_at: 2026-07-27 00:00
*/
#include <bits/stdc++.h>
using namespace std;
struct Student {
char name[25]; // 姓名
int ch, ma, en; // 三科成绩
};
int n;
int main() {
cin >> n;
Student best; // 总分最高的学生
int best_tot = -1;
for (int i = 1; i <= n; i++) {
Student cur;
cin >> cur.name >> cur.ch >> cur.ma >> cur.en;
int tot = cur.ch + cur.ma + cur.en;
if (tot > best_tot) { // 严格大于才更新,保留先出现的
best_tot = tot;
best = cur;
}
}
cout << best.name << " " << best.ch << " " << best.ma << " " << best.en;
return 0;
}复杂度
扫描 N 名学生,每名学生只处理常数个字段,时间复杂度是
总结
结构体入门题在 Python 中可以先用元组表达记录。维护“最先出现的最大值”时,并列不更新即可。