专栏文章

题解:P5741 【深基7.例10】旗鼓相当的对手 - 加强版

P5741题解参与者 4已保存评论 4

文章操作

快速查看文章及其快照的属性,并进行相关操作。

当前评论
4 条
当前快照
1 份
快照标识符
@mip1bay2
此快照首次捕获于
2025/12/03 04:32
3 个月前
此快照最后确认于
2025/12/03 04:32
3 个月前
查看原文

题目传送门

2025.6.302025.6.30 题解过审
2025.7.32025.7.3 修正了一处拼写错误,十分感谢 HuangHouze
首先,要解决存储学生信息的问题。很明显,需要采用结构体。在结构体中,需要存储如下信息:
  • 姓名;
  • 语文成绩;
  • 数学成绩;
  • 英语成绩;
  • 总分。
于是,先定义一个能存储这一坨东西的结构体。
CPP
struct stu {
    string name;
    int chinese, math, english, total; 
} a[1001];
其次,就是输入,在输入时,顺便把总分也求了。
CPP
for (int i = 0; i < n; i++) { // n 为学生总数
        cin >>
        a[i].name >>
        a[i].chinese >>
        a[i].math >>
        a[i].english;
        a[i].total = a[i].chinese + a[i].math + a[i].english;
    }
然后,就要判断“某对学生 <i,j><i,j> 的每一科成绩的分差都不大于 5,且总分分差不大于 10”。对此,可以写一个比较函数,思路是分别比较语文、数学、英语以及总分的分差,如果满足条件,则返回 1,否则返回 0。
CPP
bool qwq(stu a, stu b) {
    if (
    abs(a.chinese - b.chinese) <= 5 &&
    abs(a.math - b.math) <= 5 &&
    abs(a.english - b.english) <= 5 &&
    abs(a.total - b.total) <= 10
    )
        return 1;
    else return 0;
}
接着,就需要使用枚举,通过枚举每一对同学,找出旗鼓相当的对手。具体方法可以参考一年级时数线段的方法:
如图,先枚举端点 ii,然后从端点 i+1i+1 开始,依次与端点 ii 组成线段。而枚举每对同学,正像数线段时枚举的两个端点。到此,全篇最难的部分结束了。
最后,如果枚举到了旗鼓相当的对手,则直接输出姓名。
CPP
for (int i = 0; i < n; i++) {
    for (int j = i + 1; j < n; j++) {
        if (qwq(a[i], a[j]))
            cout << a[i].name << " " << a[j].name << endl;
    }
}
在文章的结尾,为大家奉上满分代码:
CPP
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
struct stu {
    string name;
    int chinese, math, english, total; 
} a[1001];
bool qwq(stu a, stu b) {
    if (
    abs(a.chinese - b.chinese) <= 5 &&
    abs(a.math - b.math) <= 5 &&
    abs(a.english - b.english) <= 5 &&
    abs(a.total - b.total) <= 10
    )
        return 1;
    else return 0;
}
int main() {
    int n;
    cin >> n;
    for (int i = 0; i < n; i++) {
        cin >> a[i].name >> 
        a[i].chinese >> 
        a[i].math >> 
        a[i].english;
        a[i].total = a[i].chinese + a[i].math + a[i].english;
    }
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
            if (qwq(a[i], a[j]))
                cout << a[i].name << " " << a[j].name << endl;
        }
    }
    return 0;
}

评论

4 条评论,欢迎与作者交流。

正在加载评论...