当前位置: 代码迷 >> 综合 >> HDOJ 1862 EXCEL排序(比较器)
  详细解决方案

HDOJ 1862 EXCEL排序(比较器)

热度:81   发布时间:2023-10-21 19:03:19.0

HDACM 1862

题是不难,关键在于如何加快排序速度。
我采用快排来做,自己写的快排,但是超时,所以,我借鉴前辈们的方法,调用Java中Arrays.sort()方法,排序策略由api来排,而我们只是给它设定一个比较策略。

import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;public class Main {
    public static void main(String[] args) {Scanner sc = new Scanner(System.in);int k = 0;while(sc.hasNext()){int n = sc.nextInt();int c = sc.nextInt();if (n==0) {break;}k++;Student stu[] = new Student[n];for (int i = 0; i < stu.length; i++) {stu[i] = new Student();stu[i].id = sc.nextInt();stu[i].name = sc.next();stu[i].score = sc.nextInt();}System.out.println("Case "+k+":");if (c==1) {sort1(stu);for (int i = 0; i < stu.length; i++) {stu[i].show();}continue;}if (c==2) {sort2(stu);for (int i = 0; i < stu.length; i++) {stu[i].show();}continue;}if (c==3) {sort3(stu);for (int i = 0; i < stu.length; i++) {stu[i].show();}continue;}}sc.close();}public static void sort3(Student[] s) {Arrays.sort(s,new Comparator<Student>() {@Overridepublic int compare(Student o1, Student o2) {if (o1.score==o2.score) {if (o1.id>o2.id) {return 1;}else{return -1;}}if (o1.score>o2.score) {return 1;}return -1;}});}public static void sort2(Student[] s) {Arrays.sort(s,new Comparator<Student>() {@Overridepublic int compare(Student o1, Student o2) {if (o1.name.compareTo(o2.name)==0) {if (o1.id>o2.id) {return 1;}else{return -1;}}else {if(o1.name.compareTo(o2.name)>0){return 1;}else{return -1;}}}});}public static void sort1(Student[] s){Arrays.sort(s, new Comparator<Student>() {@Overridepublic int compare(Student o1, Student o2) {if (o1.id>o2.id) {return 1;}else{return -1;}}});}
}
class Student{public int id;public String name;public int score;public void show(){System.out.printf("%06d %s %d",id,name,score);System.out.println();}}
  相关解决方案