對 N(≤100,000)條學生記錄(6位學號、姓名、成績)按指定列排序:
多組測試,N=0 結束。需輸出 `Case i:` 開頭。
雖然題目提示「不能用普通排序會超時」,但 Java Arrays.sort 使用雙軸快排(基本類型)或 TimSort(對象),對 10 萬數據完全足夠。關鍵在於正確實現 Comparator<Student>:
no。name.compareTo,相等再比 no。score,相等再比 no。學號輸出需補齊前導零至 6 位。
import java.util.*;
class Student {
int no;
String name;
int score;
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int tc = 1;
while (sc.hasNext()) {
int n = sc.nextInt();
int c = sc.nextInt();
if (n == 0 && c == 0) break;
Student[] a = new Student[n];
for (int i = 0; i < n; ++i) {
a[i] = new Student();
a[i].no = sc.nextInt();
a[i].name = sc.next();
a[i].score = sc.nextInt();
}
Comparator cmp;
if (c == 1) {
cmp = Comparator.comparingInt(s -> s.no);
} else if (c == 2) {
cmp = Comparator.comparing((Student s) -> s.name)
.thenComparingInt(s -> s.no);
} else { // c == 3
cmp = Comparator.comparingInt(s -> s.score)
.thenComparingInt(s -> s.no);
}
Arrays.sort(a, cmp);
System.out.println("Case " + tc++ + ":");
for (Student s : a) {
System.out.printf("%06d %s %d\n", s.no, s.name, s.score);
}
}
}
}
Comparator.comparing + thenComparing 鏈式構建多鍵比較器,代碼簡潔無誤。%06d 格式化自動補零,避免手動循環。Scanner 配合 hasNext() 處理多測試用例,遇 0 0 退出。