题解:P5741 【深基7.例10】旗鼓相当的对手 - 加强版
分析
题目大意:给定
这道题我们可以使用结构体存储学生信息(姓名、各科成绩、总分)。
然后遍历所有可能的学生对,检查每科分差和总分差是否符合要求,这里可以使用绝对值函数来取差。
最后将符合条件的学生对按字典序排序后输出。
代码
#include <bits/stdc++.h>
using namespace std;
struct node1 {//学生基本信息
string name;
int c, m, e, sum;
//c:语文成绩
//m:数学成绩
//e:英语成绩
}stu[1000];
struct node2 {//用两个字符串模拟字典序
string a, b;
}ans[500000];
bool cmp1(string x, string y) {//字典序比较
return x < y;
}
bool cmp2(node2 x, node2 y) {//排序学生对
if (x.a != y.a) return x.a < y.a;
return x.b < y.b;
}
int main() {
int n;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> stu[i].name >> stu[i].c >> stu[i].m >> stu[i].e;
stu[i].sum = stu[i].c + stu[i].m + stu[i].e;
}
int cnt = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (abs(stu[i].c - stu[j].c) <= 5 && abs(stu[i].m - stu[j].m) <= 5 && abs(stu[i].e - stu[j].e) <= 5 && abs(stu[i].sum - stu[j].sum) <= 10) {//abs是绝对值函数,会将参数取绝对值
if (cmp1(stu[i].name, stu[j].name)) {
ans[cnt] = {stu[i].name, stu[j].name};
} else {
ans[cnt] = {stu[j].name, stu[i].name};
}
cnt++;
}
}
}
sort(ans, ans + cnt, cmp2);
for (int i = 0; i < cnt; i++) {
cout << ans[i].a << ' ' << ans[i].b << endl;
}
return 0;
}