PTA数据结构与算法分析 37 - 7-37 模拟EXCEL排序 (25 分)

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

调用C++algorithm库中中sort算法就行了

#include<iostream>
#include<cstring>
#include<cmath>
#include<algorithm> 
using namespace std;
struct Stu
{
 char ID[10];
 char name[15];
 double score;
};
int C;
Stu st[100100];
bool cmp(Stu a,Stu b)
{
 if(C == 1){
  if(strcmp(a.ID,b.ID) < 0){
   return true;
  }
 }
 else if(C == 2){
  if(strcmp(a.name,b.name) < 0){
   return true;
  }
  else if(strcmp(a.name,b.name) == 0 && strcmp(a.ID,b.ID) < 0){
   return true;
  }
 }
 else if(C == 3){
  if(a.score < b.score){
   return true;
  }
  else if(fabs(a.score - b.score) < 1e-5 && strcmp(a.ID,b.ID) < 0){
   return true;
  }
 }
 return false; 
}
int main()
{
 freopen("D://in.txt","r",stdin);
 int N;
 cin >> N >> C;
 for(int i=0;i < N;i++){
  scanf("%s%s%lf",st[i].ID,st[i].name,&st[i].score);
 }
 sort(st,st+N,cmp);
 for(int i=0;i < N;i++){
  printf("%s %s %.0lf\n",st[i].ID,st[i].name,st[i].score);
 }
 fclose(stdin);
 return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_43189757/article/details/88756112