AcWing 429. 奖学金(传送门)
思路分析:
这是一个多关键字排序问题。
- 总分,高在前
- 语文,高在前
- 学号,小在前
这里提供两种方法:
写法1:重载小于号
AC代码:
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 310;
int n;
struct Student {
int sto, sum, chinese, math, english;
// 重载小于号,是固定语法
bool operator<(const Student &s) const {
if (sum != s.sum)
return sum > s.sum;
if (chinese != s.chinese)
return chinese > s.chinese;
return sto < s.sto;
}
} stu[N];
int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
int a, b, c;
cin >> a >> b >> c;
stu[i] = {i, a + b + c, a, b, c};
}
sort(stu + 1, stu + n + 1);
for (int i = 1; i <= 5; i++)
cout << stu[i].sto << ' ' << stu[i].sum << endl;
return 0;
}
写法2:自定义比较函数
AC代码:
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 310;
int n;
struct Student {
int sto, sum, chinese, math, english;
} stu[N];
// 自定义比较函数
bool cmp(Student& a,Student& b) {
if(a.sum != b.sum)
return a.sum > b.sum;
if(a.chinese != b.chinese)
return a.chinese > b.chinese;
return a.sto < b.sto;
}
int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
int a, b, c;
cin >> a >> b >> c;
stu[i] = {i, a + b + c, a, b, c};
}
sort(stu + 1, stu + n + 1,cmp);
for (int i = 1; i <= 5; i++)
cout << stu[i].sto << ' ' << stu[i].sum << endl;
return 0;
}