洛谷 P1093 [NOIP2007 普及组] 奖学金 题解

原题链接

P1093 [NOIP2007 普及组] 奖学金

解析

这道题还是用结构体排序做
思路就是自己写一个cmp(具体怎么排见代码)
然后sort快排

具体实施

1.初始化与输入

(1)结构体定义

struct stu
{
	int id; //学号
	int chinese; //各科成绩
	int math;
	int english;
	int total;//总分
} a[310];

(2)变量定义

int n;

(3)输入

cin >> n;
for (int i = 1; i <= n; i++)
{
	cin >> a[i].chinese >> a[i].math >> a[i].english;
	a[i].id = i;
	a[i].total = a[i].chinese + a[i].math + a[i].english;
}

2.排序

(1)cmp函数

bool cmp(stu a, stu b)
{
	if (a.total > b.total) //先比总分,如果第一个数大,那么不换
		return true;
	else if (a.total == b.total && a.chinese > b.chinese) //如果总分相等,比语文成绩,如果第一个数大,那么不换
		return true;
	else if (a.total == b.total && a.chinese == b.chinese && a.id < b.id) //如果他俩都相等,比学号。如果第一个数小,那么不换
		return true;
	else //其他情况都要换
		return false;
}

(2)主函数内sort

sort(a + 1, a + n + 1, cmp);

3.输出

for (int j = 1; j <= 5; j++) //只输出前五个学生 
{
	cout << a[j].id << ' ' << a[j].total << endl;
}

AC Code

#include <iostream>
#include <algorithm>
using namespace std;

struct stu
{
	int id;		 //学号
	int chinese; //各科成绩
	int math;
	int english;
	int total; //总分
} a[310];

int n;

bool cmp(stu a, stu b)
{
	if (a.total > b.total) //先比总分,如果第一个数大,那么不换
		return true;
	else if (a.total == b.total && a.chinese > b.chinese) //如果总分相等,比语文成绩,如果第一个数大,那么不换
		return true;
	else if (a.total == b.total && a.chinese == b.chinese && a.id < b.id) //如果他俩都相等,比学号。如果第一个数小,那么不换
		return true;
	else //其他情况都要换
		return false;
}

int main()
{
	cin >> n;
	for (int i = 1; i <= n; i++)
	{
		cin >> a[i].chinese >> a[i].math >> a[i].english;
		a[i].id = i;
		a[i].total = a[i].chinese + a[i].math + a[i].english;
	}

	sort(a + 1, a + n + 1, cmp);

	for (int j = 1; j <= 5; j++) //只输出前五个学生 
	{
		cout << a[j].id << ' ' << a[j].total << endl;
	}

	// system("pause");
	return 0;
}
posted @ 2022-12-15 20:48  第二关键句  阅读(283)  评论(0)    收藏  举报