Excel可以对一组纪录按任意指定列排序。现请编写程序实现类似功能。

输入格式:

输入的第一行包含两个正整数N(≤105) 和C,其中N是纪录的条数,C是指定排序的列号。之后有 N行,每行包含一条学生纪录。每条学生纪录由学号(6位数字,保证没有重复的学号)、姓名(不超过8位且不包含空格的字符串)、成绩([0, 100]内的整数)组成,相邻属性用1个空格隔开。

输出格式:

N行中输出按要求排序后的结果,即:当C=1时,按学号递增排序;当C=2时,按姓名的非递减字典序排序;当C=3时,按成绩的非递减排序。当若干学生具有相同姓名或者相同成绩时,则按他们的学号递增排序。

输入样例:

1
2
3
4
3 1
000007 James 85
000010 Amy 90
000001 Zoe 60

输出样例:

1
2
3
000001 Zoe 60
000007 James 85
000010 Amy 90

思路

定义sort的排序函数,对结构体排序

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include<iostream>
#include<cstring>
#include<algorithm>
const int N = 1e5 + 5;
using namespace std;
struct stu{
int id;
char name[10];
int score;
};
int c;
int cmp(stu a,stu b){
if(c==1){ //学号升序排序
return a.id<b.id;
}else if(c==2){ //姓名升序排序
if(strcmp(a.name,b.name)!=0){
return strcmp(a.name,b.name)<0;
}else{ //姓名相同则按照学号升序
return a.id<b.id;
}
}else{ //成绩升序排序
if(a.score!=b.score){
return a.score<b.score;
}else{ //成绩相同则按照学好升序
return a.id<b.id;
}
}
}
int main(){
int n;
stu s[N];
scanf("%d %d",&n,&c);
for(int i=0;i<n;i++){
scanf("%d %s %d",&s[i].id,&s[i].name,&s[i].score);
}
sort(s,s+n,cmp);//排序
for(int i=0;i<n;i++){
printf("%06d %s %d\n",s[i].id,s[i].name,s[i].score);
}
return 0;
}