Fence Repair
题目描述:
Description
农夫约翰想修牧场周围的一小段篱笆。他测量了一下篱笆,发现他需要N(1)≤ N≤ 20000)块木板,
每块木板都有一些整数长度Li(1≤ Li≤ 50000。然后,他买了一块长木板,长度刚好足以锯入N块木板
(即长度是长度Li的总和)。FJ忽略了“切口”,即锯切时锯屑损失的额外长度;你也应该忽略它。
FJ伤心地意识到,他没有用来锯木头的锯子,所以他带着这块长木板来到Farmer Don的农场,礼貌地问他是否可以借一把锯子。
农场主唐是一位壁橱资本家,他不借给FJ一把锯子,而是提议向农场主约翰收取木板N-1次切割的费用。
切割一块木头的费用正好等于它的长度。切割一块长度为21的木板需要21美分。
然后,农夫唐让农夫约翰决定切割木板的顺序和位置。帮助农夫约翰确定他能花多少钱来制作N块木板。
FJ知道他可以按照不同的顺序切割木板,这将导致不同的费用,因为产生的中间木板的长度不同。
Input
Line 1: One integer N, the number of planks
Lines 2..N+1: Each line contains a single integer describing the length of a needed plank
Output
Line 1: One integer: the minimum amount of money he must spend to make N-1 cuts
Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 91209 Accepted: 29771
样例输入输出:
Sample Input
3
8
5
8
Sample Output
34
题目分析:
- List item
题目代码:
import java.io.*;
import java.util.*;
import java.math.*;
public class Main{
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
static int Int(String s){
return Integer.valueOf(s);
}
public static void main(String[] args) throws Exception{
int n = Int(in.readLine());
PriorityQueue<Integer> heap = new PriorityQueue<Integer>(); // 小根堆
while(n --> 0){
heap.add(Int(in.readLine()));
}
long res = 0;// 答案很大,用long存
while(heap.size() != 1)
{
int min = heap.poll() + heap.poll();
res += min;
heap.add(min);
}
out.write(res + "");
out.flush();
}
}