1、题目
Excel can sort records according to any column. Now you are supposed to imitate this function.
2、输入格式
Each input file contains one test case. For each case, the first line contains two integers N (≤105) and C, where N is the number of records and C is the column that you are supposed to sort the records with. Then N lines follow, each contains a record of a student. A student's record consists of his or her distinct ID (a 6-digit number), name (a string with no more than 8 characters without space), and grade (an integer between 0 and 100, inclusive).
3、输出格式
For each test case, output the sorting result in N lines. That is, if C = 1 then the records must be sorted in increasing order according to ID's; if C = 2 then the records must be sorted in non-decreasing order according to names; and if C = 3 then the records must be sorted in non-decreasing order according to grades. If there are several students who have the same name or grade, they must be sorted according to their ID's in increasing order.
4、输入输出样例
1)样例1
3 1
000007 James 85
000010 Amy 90
000001 Zoe 60
000001 Zoe 60
000007 James 85
000010 Amy 90
2)样例2
4 2
000007 James 85
000010 Amy 90
000001 Zoe 60
000002 James 98
000010 Amy 90
000002 James 98
000007 James 85
000001 Zoe 60
3)样例3
4 3
000007 James 85
000010 Amy 90
000001 Zoe 60
000002 James 90
000001 Zoe 60
000007 James 85
000002 James 90
000010 Amy 90
5、代码
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
struct person{
int id;
char name[10];
int grade;
}per[100010];
bool compare_1(person a, person b){
return a.id < b.id; //id降序排列
}
bool compare_2(person a, person b){
//字符比较用==不能有效分辨,需要借助strcmp()函数
//if(a.name != b.name) return strcmp(a.name, b.name) < 0;
int s = strcmp(a.name, b.name); //如果字符串相等的话,返回值是0
if(s != 0) return s < 0;
else return a.id < b.id;
}
bool compare_3(person a, person b){
if(a.grade != b.grade) return a.grade < b.grade;
else return a.id < b.id;
}
int main(){
int N, C, i;
scanf("%d %d", &N, &C);
for(i = 0; i < N; i++){
scanf("%d %s %d", &per[i].id, per[i].name, &per[i].grade);
}
//一个排序函数hold不住,需要3个
if(C == 1) sort(per, per + N, compare_1);
else if(C == 2) sort(per, per + N, compare_2);
else sort(per, per + N, compare_3);
for(i = 0; i < N; i++){
printf("%06d %s %d\n", per[i].id, per[i].name, per[i].grade); //注意输出的整型,要用0填充到6个数字
}
return 0;
}
6、备注
不是太难,不要因为多写排序函数而觉得麻烦,有时候简单粗暴才是答案,哈!