中文题目链接:https://pintia.cn/problem-sets/15/problems/864


7-37 模拟EXCEL排序 (25 分)

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

   错误示例:

原因锁定:在比较学号的时候进行了类型转换,导致超时。。。

bool cmp1(struct info a, struct info b)
{
    return atoi(a.num) < atoi(b.num);
}

正确代码:

#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;

struct info{
    char num[10];
    char name[10];
    int score;
}inf[100000];

bool cmp1(struct info a, struct info b)
{
    return strcmp(a.num,b.num)<0;
}

bool cmp2(struct info a, struct info b)
{
    if(strcmp(a.name,b.name)==0) return strcmp(a.num,b.num)<0;
    return strcmp(a.name,b.name)<0;
}

bool cmp3(struct info a, struct info b)
{
    if(a.score==b.score) return strcmp(a.num,b.num)<0;
    return a.score<b.score;
}

int main(int argc, char const *argv[]){
    int n,c;
    cin>>n>>c;
    for(int i = 0; i < n; i++)
    {
        cin>>inf[i].num>>inf[i].name>>inf[i].score;
    }
    if(c==1) sort(inf,inf+n,cmp1);
    if(c==2) sort(inf,inf+n,cmp2);
    if(c==3) sort(inf,inf+n,cmp3);
    for(int i = 0; i < n; i++)
    {
        cout<<inf[i].num<<" "<<inf[i].name<<" "<<inf[i].score<<endl;
    }
}