PAT A1062

clipboard.png
含简单的一道排序题,主要注意一下cmp和sort组合使用;
之前一直搞不太清楚cmp的返回条件,所以这里做一个总结;
cmp自定义函数可以多种组合判定,就像本题的判定类似;

clipboard.png
如上图所示,唯一要注意的是return返回值。其实大可不用过于死板的背true或者false的意义,只需要看比较元素的关系;如果想要升序序列,只需要a的值小于b的值,降序序列同理;
详细代码如下所示:

#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#include<vector>
#include<algorithm>
#include<cstring>
using namespace std;
using std::vector;
struct student{
    char id[10];
    int de,cai,sum;
    int flag;
}stu[100010];
bool cmp(student a,student b){
    if(a.flag!=b.flag){
        return a.flag<b.flag;
    }else if(a.sum!=b.sum){
        return a.sum>b.sum;
    }else if(a.de!=b.de){
        return a.de>b.de;
    }else{
        return strcmp(a.id,b.id)<0;
    }
}
int N,L,H;
int main(){
    scanf("%d%d%d",&N,&L,&H);
    int number,t,v;
    int m=N;
    for(int i=0;i<N;i++){
        scanf("%s%d%d",&stu[i].id,&stu[i].de,&stu[i].cai);
        stu[i].sum=stu[i].de+stu[i].cai;
        if(stu[i].de<L||stu[i].cai<L){
            stu[i].flag=5;
            m--;
        }else if(stu[i].de>=H&&stu[i].cai>=H)
            stu[i].flag=1;
        else if(stu[i].de>=H&&stu[i].cai<H)
            stu[i].flag=2;
        else if(stu[i].de>=stu[i].cai)
            stu[i].flag=3;
        else
            stu[i].flag=4;
    }
    sort(stu,stu+N,cmp);
    printf("%d\n",m);
    for(int i=0;i<m;i++){
        printf("%s %d %d\n",stu[i].id,stu[i].de,stu[i].cai);
    } 
    system("pause");
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章