分析
题目大意:给定 $N$ 名学生的姓名和三门科目成绩,找出所有 “旗鼓相当的对手”,即两学生每科分数差不超过 $5$ 且总分差不超过 $10$。输出需按字典序排列所有符合条件的学生对。
这道题我们可以使用结构体存储学生信息(姓名、各科成绩、总分)。
然后遍历所有可能的学生对,检查每科分差和总分差是否符合要求,这里可以使用绝对值函数来取差。
最后将符合条件的学生对按字典序排序后输出。
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| #include <bits/stdc++.h> using namespace std; struct node1 { string name; int c, m, e, sum; }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) { 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; }
|