7-2 成绩排名(不偷懒用sort函数版)

输入所有同学的语文、数学成绩和他们的学号。
以语文为第一关键字,数学为第二关键字排序,按成绩降序排序。
若语文、数学成绩均相同则学号小的同学排前面。
题目保证每个同学的学号不相同。
输出排序后所有同学的学号。

输入格式:

第一行读入一个数n(2⩽n⩽105), 表示有n个同学。
接下来n行,每行有三个整数,第i行为idi​(1⩽idi​⩽500000) ai​,bi​(1⩽ai​,bi​⩽10000)。
idi​为学生的学号。
ai​为学生的语文成绩。
bi​为学生的数学成绩。

输出格式:

输出n行,每行一个数,第i行为排第i名的同学的学号

输入样例:

在这里给出一组输入。例如:

5
1 87 86
2 87 90
3 90 0
4 86 100
5 99 99

输出样例:

在这里给出相应的输出。例如:

5
3
2
1
4

代码长度限制

16 KB

时间限制

1000 ms

内存限制

256 MB

1.快速排序

#include <iostream>
#include <algorithm>

using namespace std;

struct Student {
    int id;
    int chinese;
    int math;
    bool operator<(const Student& other) const {
        if (chinese != other.chinese)
            return chinese > other.chinese;
        if (math != other.math)
            return math > other.math;
        return id < other.id;
    }//重载<符号
        bool operator>(const Student& other) const {
        if (chinese != other.chinese)
            return chinese < other.chinese;
        if (math != other.math)
            return math < other.math;
        return id > other.id;
    }//重载>符号
};

const int N = 100010;

Student students[N];

void quick_sort(Student q[],int l,int r){
    if(l>=r)return;
    Student x=q[(l+r)/2];
    int i=l-1,j=r+1;
    while(i<j){
        do i++;while(q[i]<x);
        do j--;while(q[j]>x);
        if(i<j)swap(q[i],q[j]);
    }
    quick_sort(q,l,j);
    quick_sort(q,j+1,r);
}

int main() {
    int n;
    cin >> n;
    for (int i = 0; i < n; i++) {
        cin >> students[i].id >> students[i].chinese >> students[i].math;
    }
    quick_sort(students,0,n-1);
    for (int i = 0; i < n; i++) {
        cout << students[i].id;
        if(i!=n-1)cout<<endl;
    }
    return 0;
}

 此题核心就是如何比较每个学生的数据。只需要按照题目要求将>,<重载就能实现比较了。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 16
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 16
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值