P1093 奖学金
对应章节:一、C++ 语法基础 → (十五) STL:容器、迭代器与算法。
(一) 任务与输出目标
按总分降序、语文降序、学号升序,输出前五名。
(二) 建模与推导
一个记录同时保存学号、语文和总分。比较时按优先级依次查看字段:总分不同时立即决定顺序;总分相同时比较语文;两项仍相同才比较学号。这是字典序比较,不能把三个条件直接用或连接。
(三) 手算与过程
同样总分 270 时,语文 95 排在 90 前;两人语文也相同时,学号更小的排前。
(四) 带注释实现
#include <bits/stdc++.h>
#define int long long
#define endl '\n'
using namespace std;
struct Student {
int id, chinese, total;
};
void solve() {
int n;
cin >> n;
vector<Student> a(n);
for (int i = 0; i < n; ++i) {
int math, english;
cin >> a[i].chinese >> math >> english;
a[i].id = i + 1;
a[i].total = a[i].chinese + math + english;
}
sort(a.begin(), a.end(), [](const Student& x, const Student& y) {
if (x.total != y.total)
return x.total > y.total; // 第一排序字段。
if (x.chinese != y.chinese)
return x.chinese > y.chinese; // 第二字段。
return x.id < y.id; // 同分时按学号决定先后。
});
for (int i = 0; i < 5; ++i)
cout << a[i].id << ' ' << a[i].total << '\n';
}
signed main() {
ios::sync_with_stdio(false); // 关闭同步,使用 cin 与 cout 完成输入输出。
cin.tie(0), cout.tie(0);
int T = 1; // 本题读入一组数据。
// cin >> T; // 题目给出测试组数时开启,并在 solve 中处理一组。
while (T--)
solve();
}(五) 复杂度
时间 \(O(n\log n)\),保存学生记录占 \(O(n)\)。