[PAT解题报告] List Sorting

简单题, 每个人有id, name, grade 三个指标,输入一个维度(1-3),按照这个指标排序。id肯定不同,如果发现要排序的那一维相同,就让id小的在前。
C++ STL algorithm库里的sort函数,只要给定cmp函数,就能按照它排序(返回true表示小于),所以这个题无非就是实现3个cmp函数而已,id的最简单,其他两个需要在相等的时候靠id区分。
建议使用C的scanf , printf,否则会超时。

代码:
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>

using namespace std;

struct node {
string id, name;
int score;
};

char s[22];
node a[100005];

bool cmp1(const node &a,const node &b) {
    return a.id < b.id;
}

bool cmp2(const node &a,const node &b) {
    return (a.name <  b.name) || ((a.name == b.name) && cmp1(a,b));
}

bool cmp3(const node &a,const node &b) {
    return (a.score < b.score) || ((a.score == b.score) && cmp1(a,b));
}

int main() {
int n,c;
    scanf("%d%d",&n,&c);
    for (int i = 0; i < n; ++i) {
        scanf("%s",s);
        a[i].id = s;
        scanf("%s%d",s,&a[i].score);
        a[i].name = s;
    }
    if (c == 1) {
        sort(a, a + n, cmp1);
    }
    else if (c == 2) {
        sort(a, a + n, cmp2);
    }
    else {
        sort(a, a + n, cmp3);
    }
    for (int i = 0; i < n; ++i) {
        printf("%s %s %d\n",a[i].id.c_str(),a[i].name.c_str(),a[i].score);
    }
    return 0;
}
原题链接: http://www.patest.cn/contests/pat-a-practise/1028


全部评论

相关推荐

祈求顺利毕业😁:简历很好了,多投吧牛油😂。主要是环境不好,大家也卷
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务