PAT A1028 List Sorting 列表排序【简单排序 】

Excel can sort records according to any column. Now you are supposed to imitate this function.

Excel可以根据任一列对记录进行排序,现在你需要来模仿这个功能

Input Specification:

Each input file contains one test case. For each case, the first line contains two integers N (≤10​^5​​) 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).

第一行包含两个整数N(<10^5)和C,N是记录的总数量,C是记录的列数。之后有N行,每一行包含了一个学生记录。一个学生记录包括他第一无二的ID(一个6位数字) 名字(不超过8个字符的字符串,无空格) 和分数(在0-100之间的整数,包括0和100)

Output Specification:

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.

输出N行的排序结果。如果C=1,那么记录需要根据ID号以递增顺序排列。如果C=2,那么记录需要根据姓名按非递减顺序排列。如果C=3,那么记录要根据分数非递减顺序排列。如果有几个学生有相同的姓名或者分数,按照ID号递增顺序排列

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=100010;

struct Student{
	int id;
	char name[10];
	int grade;
}stu[maxn];
int C;
bool cmp(Student a,Student b){
    if(C==2&&strcmp(a.name,b.name)!=0) return strcmp(a.name,b.name)<0;
    else if(C==3&&a.grade!=b.grade) return a.grade<b.grade;
    else  return a.id<b.id;
}
int main(){
	int n;
	scanf("%d%d",&n,&C);
	for(int i=0;i<n;i++){
		scanf("%d %s %d",&stu[i].id,stu[i].name,&stu[i].grade);
	}
	sort(stu,stu+n,cmp);
	for(int i=0;i<n;i++){
		printf("%06d %s %d\n",stu[i].id,stu[i].name,stu[i].grade);
	}
	return 0;
}

出错的地方:打印学生id时,注意%06d 不然结果会错误

上一篇:[leetcode] Minimum Number of K Consecutive Bit Flips


下一篇:Python编程:方差、标准差、均方差、均方根值、均方误差、均方根误差