思路:
主要是弄清楚如何写出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;
}
坑:
- 使用了string类型和cin、cout后时间超限很多,下次不敢用了-_-||