题解 | #成绩排序#

成绩排序

https://www.nowcoder.com/practice/8e400fd9905747e4acc2aeed7240978b

#include <algorithm>
#include <iostream>
#include <vector>
#include <utility>
#include <string>
using namespace std;

typedef pair<string, int> ScoreRcd;

bool AscendCmp(ScoreRcd p1, ScoreRcd p2);
bool DescendCmp(ScoreRcd p1, ScoreRcd p2);

int main() {
    int cnt = 0;
    cin >> cnt;
    if(cnt<1 || cnt>200)    return -1;

    int mode = 0;
    cin >> mode; //mode =0 descend 1-ascend

    //vector<ScoreRcd > recvec;
    vector<ScoreRcd> recvec;
    string tempname;
    int tempscore;
    for(int i=0; i<cnt; i++)
    {
        cin >> tempname;
        cin >> tempscore;
        recvec.push_back(make_pair(tempname, tempscore));
        //pair<string, int> temprcd = make_pair(tempname, tempscore);
        //recvec.push_back();
    }
    if(mode == 0)
    {
        stable_sort(recvec.begin(), recvec.end(),DescendCmp);
    }
    else if(mode == 1)
    {
        stable_sort(recvec.begin(), recvec.end(), AscendCmp);
    }

    for(int i=0; i<cnt; i++)
    {
        cout << recvec[i].first << " "<<recvec[i].second <<endl;
    }
    return 0;
}

//数据结构:vector<pair<string, int> > scoretbl;
//排序方式:两种:升序和降序
//额外要求:相同成绩按先录入排列在前,可以用泛型算法 stable_sort
//排序算法:stable_sort()

bool AscendCmp(ScoreRcd p1, ScoreRcd p2)
{
    return p1.second < p2.second;
}

bool DescendCmp(ScoreRcd p1, ScoreRcd p2)
{
    return p1.second > p2.second;
}

全部评论

相关推荐

认真搞学习:28小登的建议,投算法岗不要写什么物理竞赛,互联网+,多写点项目,用什么算法做了什么。还有本科算法是不可能的开发你这个也没有项目啊
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务