51nod--1117-聪明的木匠

来源:互联网 发布:汇众教育知乎 编辑:程序博客网 时间:2024/04/29 06:50

一位老木匠需要将一根长的木棒切成N段。每段的长度分别为L1,L2,……,LN(1 <= L1,L2,…,LN <= 1000,且均为整数)个长度单位。我们认为切割时仅在整数点处切且没有木材损失。
木匠发现,每一次切割花费的体力与该木棒的长度成正比,不妨设切割长度为1的木棒花费1单位体力。例如:若N=3,L1 = 3,L2 = 4,L3 = 5,则木棒原长为12,木匠可以有多种切法,如:先将12切成3+9.,花费12体力,再将9切成4+5,花费9体力,一共花费21体力;还可以先将12切成4+8,花费12体力,再将8切成3+5,花费8体力,一共花费20体力。显然,后者比前者更省体力。
那么,木匠至少要花费多少体力才能完成切割任务呢?
Input
第1行:1个整数N(2 <= N <= 50000)
第2 - N + 1行:每行1个整数Li(1 <= Li <= 1000)。
Output
输出最小的体力消耗。
Input示例
3
3
4
5
Output示例
19

import java.io.IOException;import java.util.Comparator;import java.util.PriorityQueue;import java.util.Queue;import java.util.Scanner;/* * 思路:先选择最小的两个组成一个然后在放进队列在选取两个最小的在相加。直到结束。 *  * */public class Main {    public static void main(String[] args) throws NumberFormatException, IOException {        Scanner sc = new Scanner(System.in);        int n = sc.nextInt();        Comparator<Integer> c = new Comparator<Integer>() {//比较器(其实不用写比较器的,这里只是为了让自己熟悉一下构造器)            @Override            public int compare(Integer o1, Integer o2) {                return o1.compareTo(o2);            }        };        Queue<Integer> queue = new PriorityQueue<>(c);//优先级队列        for(int i = 0 ; i < n; i++ ){            queue.add(sc.nextInt());        }        int temp1=0 ,temp2=0;        int sum = 0;        while(queue.size()>1){            temp1 = queue.poll();            temp2 = queue.poll();            sum += temp1 + temp2;            queue.add(temp1+temp2);        }        System.out.println(sum);    }}
0 0