avatar
fireworks99
keep hungry keep foolish

HJ68 成绩排序

题目描述

给定一些同学的信息(名字,成绩)序列,请你将他们的信息按照成绩从高到低或从低到高的排列,相同成绩都按先录入排列在前的规则处理。

示例

jack 70
peter 96
Tom 70
smith 67

从高到低 成绩
peter 96
jack 70
Tom 70
smith 67

从低到高

smith 67
jack 70
Tom 70
peter 96

思路

结构体排序 + stable_sort

Code

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

struct Student
{
    string name;
    int score;
};

bool cmp_0(Student a, Student b) {
    return a.score > b.score;
}

bool cpm_1(Student a, Student b) {
    return a.score < b.score;
}


int main() {
    freopen("00input.txt", "r", stdin);
    int n;
    Student s[205];
    while (cin >> n)
    {
        int kind;
        cin >> kind;
        for(int i = 0; i < n; ++i)
        {
            cin >> s[i].name;
            cin >> s[i].score;
        }
        stable_sort(s, s + n, kind ? cpm_1 : cmp_0);
        for(int i = 0; i < n; ++i)
        {
            cout << s[i].name << ' ' << s[i].score << '\n';
        }
    }

    return 0;
}
Site by Baole Zhao | Powered by Hexo | theme PreciousJoy