【基础算法】多关键字排序专题

429. 奖学金

重载小于号写法

#include <iostream>
#include <algorithm>
#include <cstring>

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()
{
    scanf("%d", &n);
    for(int i = 1; i <= n; i ++ )
    {
        int a, b, c;
        scanf("%d%d%d", &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 <algorithm>
#include <cstring>

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()
{
    scanf("%d", &n);
    for(int i = 1; i <= n; i ++ )
    {
        int a, b, c;
        scanf("%d%d%d", &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;
}
posted @ 2022-05-04 18:18  Tshaxz  阅读(41)  评论(0编辑  收藏  举报
Language: HTML