考研算法 2022.2.23

122 阅读1分钟

考研算法

题目链接

题目要求

稳定排序 stable_sort() 快速排序,堆排序都是不稳定排序

知识点

algorithm库

在这里是为了引入stable_sort() C++ 算法库(Algorithms library)为 C++ 程序提供了大量可以用来对容器及其它序列进行算法操作的函数

bool operator< (const student& t) const

运算符重载 结构体内嵌比较函数bool operator < (const node &x) const {}

greater()

完成排序 (1条消息) C++:std::greater()、std::less()、自定义比较函数的规则_sandalphon4869的博客-CSDN博客_std::greater

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

const int N = 1010;
int n,m;
struct student
{
    int score;
    string name;
    bool operator< (const student& t) const
    {
        return score <t.score;
    }
    bool operator> (const student& t) const
    {
        return score >t.score;
    }
}q[N];
int main()
{
    cin>>n>>m;
    for (int i = 0; i < n; i ++ )
    {
        cin>>q[i].name>>q[i].score;
    }
    if (!m){
        stable_sort(q,q+n,greater<student>());
    }
    else
    {
        stable_sort(q,q+n);
    }
    for (int i = 0; i < n; i ++ )
    {
        cout << q[i].name<<' '<<q[i].score<<endl;
    }
    return 0;
}

sort用法

cmp,key,reverse Python List sort()方法 | 菜鸟教程 (runoob.com)

n=int(input())
k=int(input())
lis=[]
def takeSecond(x):
    return x[1]
for i in range(n):
    name,score=input().split()
    score=int(score)
    lis.append((name,score))

if k==0:
    lis.sort(key=takeSecond,reverse=True)
else:
    lis.sort(key=takeSecond)

for i in range(n):
    print(lis[i][0]+' '+str(lis[i][1]))