Excel可以对一组纪录按任意指定列排序。现请编写程序实现类似功能。
输入格式:
输入的第一行包含两个正整数N(≤10^5) 和C,其中N是纪录的条数,C是指定排序的列号。之后有 N行,每行包含一条学生纪录。每条学生纪录由学号(6位数字,保证没有重复的学号)、姓名(不超过8位且不包含空格的字符串)、成绩([0, 100]内的整数)组成,相邻属性用1个空格隔开。
输出格式:
在N行中输出按要求排序后的结果,即:当C=1时,按学号递增排序;当C=2时,按姓名的非递减字典序排序;当C=3时,按成绩的非递减排序。当若干学生具有相同姓名或者相同成绩时,则按他们的学号递增排序。
输入样例:
3 1
000007 James 85
000010 Amy 90
000001 Zoe 60
输出样例:
000001 Zoe 60
000007 James 85
000010 Amy 90
思路:利用sort直接将自定义的类型根据题目的三种要求进行排序。
技巧:
ios_base::sync_with_stdio(false);
cin.tie(0);
这两行代码可以加快cin和cout的速度。
完整的AC代码:
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
typedef struct OOO {
string xh, nm;
int cj;
}JJ;
JJ p[100005];
bool cmp1(JJ a, JJ b) {
return a.xh < b.xh;
}
bool cmp2(JJ a, JJ b) {
if (a.nm == b.nm) {
return a.xh < b.xh;
}
else {
return a.nm < b.nm;
}
}
bool cmp3(JJ a, JJ b) {
if (a.cj == b.cj) {
return a.xh < b.xh;
}
else {
return a.cj < b.cj;
}
}
int main() {
int n, c;
ios_base::sync_with_stdio(false);
cin.tie(0);
//cout.tie(0);
cin >> n >> c;
//scanf_s("%d %d", &n, &c);
for (int i = 0; i < n; i++) {
cin >> p[i].xh >> p[i].nm >> p[i].cj;
//scanf_s("%s %s %d", p[i].xh, p[i].nm, &p[i].cj);
}
if (c == 1) {
sort(p, p + n, cmp1);
}
else if (c == 2) {
sort(p, p + n, cmp2);
}
else {
sort(p, p + n, cmp3);
}
for (int i = 0; i < n; i++) {
cout << p[i].xh << " " << p[i].nm << " " << p[i].cj << endl;
}
return 0;
}
另外的一种AC代码:
#include <cstdio>
#include <string.h>
#include <algorithm>
using namespace std;
// 定义一个学生结构体
struct student{
int num;
char name[9];
int score;
}s[100000];
// 定义三个排序函数
// 按学号递增排序
int s1(student a,student b)
{
if(a.num<b.num)
return 1;
return 0;
}
// 按姓名的非递减字典序排序
int s2(student a,student b)
{
if(strcmp(a.name,b.name)<0)
return 1;
else if(strcmp(a.name,b.name)==0 && a.num<b.num)
return 1;
return 0;
}
// 相同姓名或者相同成绩时,则按他们的学号递增排序
int s3(student a,student b)
{
if(a.score<b.score)
return 1;
else if((a.score==b.score) && a.num<b.num)
return 1;
return 0;
}
int main (){
int N,C;
scanf("%d%d",&N,&C);
for(int i=0;i<N;i++)
scanf("%d %s %d",&s[i].num,s[i].name,&s[i].score);
//用c++中内置的的sort排序函数,按照自定义的三种方式排序
if(C==1)
sort(s,s+N,s1);
else if(C==2)
sort(s,s+N,s2);
else if(C==3)
sort(s,s+N,s3);
for(int i=0;i<N;i++)
printf("%06d %s %d\n",s[i].num,s[i].name,s[i].score);
return 0;
}