1. 程式人生 > >PAT 1028 List Sorting (25分) 用char[],不要用string

PAT 1028 List Sorting (25分) 用char[],不要用string

### 題目 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`,每個學生的資訊包括`ID`(6位數字),姓名(長度最多為`8`的字串,無空格),分數(`0-100`)。根據數字`C`的取值,對學生資訊按照不同策略進行排序,最終輸出排序後的學生資訊: C=1:按 ID 遞增; C=2:按姓名遞增,如果同名,按ID遞增; C=3:按分數遞增,如果同分,按ID遞增。 ### 思路分析 這不就是三種排序策略就完了嗎? - 首先建立結構體 `Student` 儲存學生資訊,注意 `name` 欄位**不要用`string`**!!!,否則你最後一個測試點會是 **執行超時**,實際是記憶體溢位! ![在這裡插入圖片描述](https://img-blog.csdnimg.cn/20200518201202701.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3d3YW5nX2Rldg==,size_16,color_FFFFFF,t_70) 其實可以想想,**題目給出說明姓名欄位長度不超過10個字元**,怎麼可能沒用呢,是吧! - 如何排序,因為我們使用sort()函式對整個結構體陣列進行排序,自己實現的比較函式只能是這樣`int cmp(Student a, Student b)`,所以我們要把 `C` 定義成一個**全域性變數**,然後在這個函式中根據 C的取值進行不同的邏輯實現,當然你也可以實現三個比較函式,但我覺得沒有必要。 ### 程式碼 題目比較簡單,程式碼註釋也挺詳細,沒什麼好說的。有個地方需要注意:**學號是6位**數字,輸出必須用`printf("%06d", id)`格式化。 ```cpp #