3. 题目解析

方法一：sort()+自定义排序+常规解法

``````#include <iostream>
#include <algorithm>
#include <string>

using namespace std;

struct student {
int a, b, c, d, sum;
string name;
};

bool cmp1(student a, student b) {
if (a.a == b.a) {
return a.name < b.name;
}
return a.a > b.a;
}

bool cmp2(student a, student b) {
if (a.b == b.b) {
return a.name < b.name;
}
return a.b > b.b;
}

bool cmp3(student a, student b) {
if (a.c == b.c) {
return a.name < b.name;
}
return a.c > b.c;
}

bool cmp4(student a, student b) {
if (a.d == b.d) {
return a.name < b.name;
}
return a.d > b.d;
}

bool cmp5(student a, student b) {
if (a.sum == b.sum) {
return a.name < b.name;
}
return a.sum > b.sum;
}

int main() {
int n;
student s[105];
cin >> n;
for (int i = 0; i < n; i++) {
cin >> s[i].name >> s[i].a >> s[i].b >> s[i].c >> s[i].d;
s[i].sum = s[i].a + s[i].b + s[i].c + s[i].d;
}
sort(s, s + n, cmp1);
for (int i = 0; i < 4; i++) {
if (i) {
cout << " ";
}
cout << s[i].name;
}
cout << endl;
sort(s, s + n, cmp2);
for (int i = 0; i < 4; i++) {
if (i) {
cout << " ";
}
cout << s[i].name;
}
cout << endl;
sort(s, s + n, cmp3);
for (int i = 0; i < 4; i++) {
if (i) {
cout << " ";
}
cout << s[i].name;
}
cout << endl;
sort(s, s + n, cmp4);
for (int i = 0; i < 4; i++) {
if (i) {
cout << " ";
}
cout << s[i].name;
}
cout << endl;
sort(s, s + n, cmp5);
for (int i = 0; i < 4; i++) {
if (i) {
cout << " ";
}
cout << s[i].name;
}
cout << endl;
return 0;
}
``````

方法二：sort()+宏定义+自定义排序+巧妙解法

``````#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <string>
using namespace std;

struct Student {
string name;
int score[4];
int total_score;
cin >> name;
for (int i = 0; i < 4; i++) {
cin >> score[i];
total_score += score[i];
}
return ;
}
};

#define MAX_N 100
#define cmp(x, y) bool cmp##x(Student &s1, Student &s2) { \
if (s1.y > s2.y) return true; \
if (s1.y == s2.y && s1.name < s2.name) return true; \
return false; \
}

Student stu[MAX_N];

cmp(0, score[0]);
cmp(1, score[1]);
cmp(2, score[2]);
cmp(3, score[3]);
cmp(total, total_score);

int main() {
int n;
cin >> n;
for (int i = 0; i < n; i++) {
}
sort(stu, stu + n, cmp0);
for (int i = 0; i < 4; i++) {
if (i) cout << " ";
cout << stu[i].name;
}
cout << endl;
sort(stu, stu + n, cmp1);
for (int i = 0; i < 4; i++) {
if (i) cout << " ";
cout << stu[i].name;
}
cout << endl;
sort(stu, stu + n, cmp2);
for (int i = 0; i < 4; i++) {
if (i) cout << " ";
cout << stu[i].name;
}
cout << endl;
sort(stu, stu + n, cmp3);
for (int i = 0; i < 4; i++) {
if (i) cout << " ";
cout << stu[i].name;
}
cout << endl;
sort(stu, stu + n, cmptotal);
for (int i = 0; i < 4; i++) {
if (i) cout << " ";
cout << stu[i].name;
}
cout << endl;
return 0;
}
``````