Fence Repair 贪心算法 Java实现

Fence Repair

题目描述:

Description
	农夫约翰想修牧场周围的一小段篱笆。他测量了一下篱笆,发现他需要N1)≤ N20000)块木板,
	每块木板都有一些整数长度Li1Li50000。然后,他买了一块长木板,长度刚好足以锯入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();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值