《算法笔记》codeup_100000581_C

思路:

主要是弄清楚如何写出cmp函数

解答:

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

struct Student {
    char id[10];
    char name[10];
    int score;
};

bool cmp_1(Student a, Student b) {
    return strcmp(a.id, b.id) < 0;
}

bool cmp_2(Student a, Student b) {
    if(strcmp(a.name, b.name) != 0) 
        return strcmp(a.name, b.name) < 0;
    else
        return strcmp(a.id, b.id) < 0;
}

bool cmp_3(Student a, Student b) {
    if (a.score != b.score) 
        return a.score < b.score;
    else
        return strcmp(a.id, b.id) < 0;
}

/* 使用string的结构体和cmp函数
struct Student {
    string id;
    string name;
    int score;
};

bool cmp_1(Student a, Student b) {
    return a.id < b.id;
}

bool cmp_2(Student a, Student b) {
    if(a.name != b.name) 
        return a.name < b.name;
    else
        return a.id < b.id;    
}

bool cmp_3(Student a, Student b) {
    if(a.score != b.score) 
        return a.score < b.score;
    else
        return a.id < b.id;    
}
*/

int main() {
    int stu_num;       // 学生数量
    int mode;
    int case_num = 1;  // case从1开始计数
    
    while(1) {
        scanf("%d %d", &stu_num, &mode);
        
        if(stu_num == 0)
            break;
        
        Student stu_arr[stu_num];

        for(int i = 0; i <= stu_num - 1; i++) {
            scanf("%s %s %d", stu_arr[i].id, stu_arr[i].name, &stu_arr[i].score);
        }

        if(mode == 1) {
            sort(stu_arr, stu_arr + stu_num, cmp_1);
        }
        else if(mode == 2) {
            sort(stu_arr, stu_arr + stu_num, cmp_2);
        }
        else if(mode == 3) {
            sort(stu_arr, stu_arr + stu_num, cmp_3);
        }
    
        printf("Case %d:\n", case_num);

        for(int i =0; i <= stu_num - 1; i++) {
            printf("%s %s %d\n", stu_arr[i].id, stu_arr[i].name, stu_arr[i].score);
        }

        case_num++;
    }
    return 0;
}

坑:

  1. 使用了string类型和cin、cout后时间超限很多,下次不敢用了-_-||
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值