C++算法题-旗鼓相当的对手

题目

题目来自洛谷,链接:https://www.luogu.com.cn/problem/P5728

题解

首先要解决学生分数的存储问题,选择一个数据结构,可以使用二维数组、结构体。不过这次我们使用对象并使用构造函数来化简一些代码工作。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class student
{
  public:
    int chinese;
    int math;
    int english;
    int sum;
    student()
    {
        std::cin >> chinese >> math >> english;
        sum = chinese + math + english;
    }
};

每个学生的语数英成绩和总分都可以保存在这个对象内,而且通过构造函数可以在对象创建时顺便获取信息并进行总分求和。

在完成数据结构之后,现在来看看题目关键部分:

如果某对学生 ⟨i,j⟩ 的每一科成绩的分差都不大于 5,且总分分差不大于 10,那么这对学生就是“旗鼓相当的对手”。

判断条件非常简单。创建一个函数,专门用于进行判断,返回布尔值。

1
2
3
4
5
6
7
8
bool vs(student a, student b)
{
    if (abs(a.chinese - b.chinese) > 5 || abs(a.math - b.math) > 5 || abs(a.english - b.english) > 5 || abs(a.sum - b.sum) > 10)
    {
        return false;
    }
    return true;
}

主函数同样的,获取成绩,进行比较,输出对数。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
int main(int argc, char *argv[])
{
    int n, count = 0;
    std::vector<student> list;
    std::cin >> n;
    for (int i = 0; i < n; i++)
    {
        student newOne;
        list.emplace_back(newOne);
    }

    for (int i = 0; i < n; i++)
        for (int j = i + 1; j < n; j++)
            if (vs(list.at(i), list.at(j)) == true)
                count++;

    std::cout << count;

    return 0;
}

(好水的题解啊……)

萌ICP备20241614号