| ||||||||||
| Online Judge | Problem Set | Authors | Online Contests | User | ||||||
|---|---|---|---|---|---|---|---|---|---|---|
| Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest | |||||||||
Java 优先队列import java.util.PriorityQueue;
import java.util.Scanner;
public class FenceRepair {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while(in.hasNext()){
long cost = 0; //总代价
PriorityQueue queue = new PriorityQueue(); //存放木板的长度 注意不能识别泛型
int N =in.nextInt();
for (int i = 0; i < N; i++) {
//入队N块木板
queue.offer(in.nextInt());
}
while (queue.size() > 1){ //只要队列中的元素大于1 就仍然需要合并
int firstMin = ((Integer)queue.poll()).intValue(); //第一小
int secondMin = ((Integer)queue.poll()).intValue(); //第二小
//没有自动拆箱 只能手动转换类型
int temp = firstMin+ secondMin; //合并两块最小的木板
cost += temp;
queue.add(temp); //合并后的木板从新入队
}
System.out.println(cost);
}
}
}
Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator