藍橋杯【答疑】
題目描述

分析
這是一個貪心演算法,要所得的時刻之和最小,而且下一個同學需要等上一個同學結束以后才能進行,因此需要對所耗總時間進行有小到大的排序,總時間相同的同學則對前兩步時間之和有小到大進行排序,最后算出時間之和即可,
代碼
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class Tset {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
Stu[] stu = new Stu[n];
for(int i=0;i<n;i++){
stu[i] = new Stu(scan.nextInt(),scan.nextInt(),scan.nextInt());
}
scan.close();
Arrays.sort(stu, new Comparator<Stu>(){//自己定義一個比較器進行比較
@Override
public int compare(Stu o1,Stu o2) {//比較回傳1,o1放后面,回傳2,o2放后面
if(o1.all-o2.all>0){
return 1;
} else if (o1.all-o2.all<0) {
return -1;
} else if (o1.two>=o2.two) {
return 1;
}else {
return -1;
}
}
});
long min=0,time=0;//注意要使用long型,不然結果會超出
for(int i=0;i<n;i++){
min+=stu[i].s+stu[i].a+time;
time+=stu[i].all;
}
System.out.println(min);
}
}
//Stu類,用于儲存n個學生的資訊
class Stu{
int s;
int a;
int e;
int two;
int all;
Stu(int s,int a,int e){
this.s = s;
this.a = a;
this.e = e;
two = s+a;
all = s+a+e;
}
}
代碼分析
在該段代碼中,最重要的是使用了java.util.Comparator中的介面,并重寫了int compare(T o1,T o2)方法,對o1,o2進行比較并排序,回傳1時o1放在o2后,反之放在o2前,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/548461.html
標籤:其他
上一篇:FastDFS并發問題的排查經歷
