【简洁代码】1028 List Sorting (25 分)_26行代码AC

立志用最少的代码做最高效的表达


PAT甲级最优题解——>传送门


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

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).

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.

Sample Input 1:
3 1
000007 James 85
000010 Amy 90
000001 Zoe 60
Sample Output 1:
000001 Zoe 60
000007 James 85
000010 Amy 90

Sample Input 2:
4 2
000007 James 85
000010 Amy 90
000001 Zoe 60
000002 James 98
Sample Output 2:
000010 Amy 90
000002 James 98
000007 James 85
000001 Zoe 60

Sample Input 3:
4 3
000007 James 85
000010 Amy 90
000001 Zoe 60
000002 James 90
Sample Output 3:
000001 Zoe 60
000007 James 85
000002 James 90
000010 Amy 90


题意输入学生记录,要求按规则排序。 给定n, c。n条记录,排序, k=1则按学号升序排序,k=2则按名字升序排序,k=3则按成绩升序排序。 如果名字或成绩相等,则按学号升序排序

分析主要考察自定义排序,具体逻辑见我的代码。


二更网上有些同学用cin、cout导致超时。因此建议用c写。 其实加上ios::sync_with_stdio(false);这行代码后(取消流同步),C++反而比C要快一些。


#include
using namespace std;

struct recode{
     
	string id, name;
	int score;
}re[100010];
int n, c; 

bool cmp(recode r1, recode r2) {
     
	if(c == 1) return r1.id < r2.id;
	if(c==2) 
		if(r1.name != r2.name) return r1.name < r2.name;
		else return r1.id < r2.id;
	else if(c == 3)
		if(r1.score != r2.score) return r1.score < r2.score;
		else return r1.id < r2.id;
}

int main() {
     
	ios::sync_with_stdio(false); 
	cin >> n >> c;
	for(int i = 0; i < n; i++) 
		cin >> re[i].id >> re[i].name >> re[i].score;
		
	sort(re, re+n, cmp);
	
	for(int i = 0; i < n; i++) 
		cout << re[i].id << ' ' << re[i].name << ' ' << re[i].score << '\n';
	
	return 0;
}

耗时:

【简洁代码】1028 List Sorting (25 分)_26行代码AC_第1张图片


       ——记住,不要愤怒,因为愤怒会降低你的智慧;也不要仇恨自己的敌人,因为仇恨会使你丧失判断力。与其恨自己的敌人,不如拿他来为我所用。

你可能感兴趣的:(PAT甲级,PAT,PAT甲级)