AcWing 429.奖学金
题解:奖学金题目描述思路分析代码实现题目描述题目链接:https://www.acwing.com/problem/content/431/思路分析第一种方法:重载小于号第二种方法:自定义比较函数代码实现重载小于号#include <iostream>#include <cstring>#include <algorithm>using namespace st
·
题目描述
题目链接:
https://www.acwing.com/problem/content/431/
思路分析
- 第一种方法:重载小于号
- 第二种方法:自定义比较函数
代码实现
重载小于号
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 310;
int n;
struct Person
{
int id, sum, a, b, c;
bool operator< (const Person& t) const
{
if (sum != t.sum) return sum > t.sum;
if (a != t.a) return a > t.a;
return id < t.id;
}
}q[N];
int main()
{
cin >> n;
for (int i = 1; i <= n; i ++ )
{
int a, b, c;
cin >> a >> b >> c;
q[i] = {i, a + b + c, a, b, c};
}
sort(q + 1, q + n + 1);
for (int i = 1; i <= 5; i ++ )
cout << q[i].id << ' ' << q[i].sum << endl;
return 0;
}
自定义比较函数
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 310;
int n;
struct Person
{
int id, sum, a, b, c;
}q[N];
bool cmp(Person& a, Person& b)
{
if (a.sum != b.sum)
return a.sum > b.sum;
if (a.a != b.a)
return a.a > b.a;
return a.id < b.id;
}
int main()
{
cin >> n;
for (int i = 1; i <= n; i ++ )
{
int a, b, c;
cin >> a >> b >> c;
q[i] = {i, a + b + c, a, b, c};
}
sort(q + 1, q + n + 1, cmp);
for (int i = 1; i < = 5; i ++ )
cout << q[i].id << ' ' << q[i].sum << endl;
return 0;
}
更多推荐
已为社区贡献4条内容
所有评论(0)