【深基5.例5】旗鼓相当的对手
题目描述
现有 N(N≤1000) 名同学参加了期末考试,并且获得了每名同学的信息:语文、数学、英语成绩(均为不超过 150 的自然数)。如果某对学生 <i,j> 的每一科成绩的分差都不大于 5,且总分分差不大于 10,那么这对学生就是“旗鼓相当的对手”。现在想知道这些同学中,有几对“旗鼓相当的对手”?同样一个人可能会和其他好几名同学结对。
输入格式
第一行一个正整数 N。
接下来 N 行,每行三个整数,其中第 ii 行表示第 ii 名同学的语文、数学、英语成绩。最先读入的同学编号为 1。
输出格式
输出一个个整数,表示“旗鼓相当的对手”的对数。
输入输出样例
输入 #1复制
3
90 90 90
85 95 90
80 100 91
输出 #1复制
2
结构体数组去处理即可
AC代码(C++)
#include <iostream>
#include <cmath>
using namespace std;
struct student
{
float chinese;
float math;
float english;
float addScore;
};
bool getFriend(struct student& A, struct student& B)
{
//成绩有可能是浮点数,成绩相减有可能出现负数所以需要取绝对值
if (fabs(A.addScore - B.addScore) > 10)
return false;
if (fabs(A.chinese - B.chinese) > 5 || fabs(A.english - B.english) > 5 || fabs(A.math - B.math) > 5)
return false;
return true;
}
int main()
{
student stu[1010] = { 0 };
int max_stu;
int max_now;
int count = 0;
cin >> max_stu;
for (int i = 0; i < max_stu; i++)
{
cin >> stu[i].chinese >> stu[i].math >> stu[i].english;
//实时更新总分
stu[i].addScore = stu[i].chinese + stu[i].english + stu[i].math;
max_now = i;
for (int j = 0; j < max_now; j++)
{
//判断是否符合条件
if (getFriend(stu[i], stu[j]))
count++; //统计
}
}
cout << count;
return 0;
}