【简洁代码】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<bits/stdc++.h> 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的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 1027 Colors in Mars
- 下一篇: 【19行代码AC,简洁】1029 Med