聪明木匠的切割问题

一位老木匠需要将一根长的木棒切成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示例
19

//代码块
package Eleve;

import java.util.Scanner;

public class the_Old_Carpenter {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner sc = new Scanner(System.in);
    int a = sc.nextInt();
    int sum = 0;
    //定义一个数组来存放所切的段数
    int[] array = new int[a];
    //将所要切得每一段的具体长度输入,组成一个数组
    for(int i=0;i<array.length;i++){
        array[i] = sc.nextInt();
    }
    //对所输入的数字进行排序
    for(int i= 0;i<array.length-1;i++){
        for(int j=0;j<array.length-1-i;j++){
            if(array[j]>array[j+1]){
                int m=0;
                m = array[j];
                array[j] = array[j+1];
                array[j+1] = m;
            }
        }
    }
    //切割的时候应该是先从最大的开始切
    for(int i = array.length-2;i>=0;i--){
        int sum1 = 0;
         for(int j = i;j>=0;j--){
             sum1+=array[j];
         }
         sum = sum+array[i+1]+sum1;
    }
    System.out.print("最短时间为:"+sum);

}

}

猜你喜欢

转载自blog.csdn.net/new_buff_007/article/details/77962078