Algorithm programming (Java) # rope cut issue

Copyright: Author: xp_9512 Source: CSDN Copyright: This article is a blogger original article, reproduced, please attach Bowen link! Original: https://blog.csdn.net/qq_40981804/article/details/89556812

Problem Description

There N rope, the i-th length Li, and m is now required as long rope. You can cut at random (not spliced) n-rope, which calculates how much the longest length of rope m?

Input Description:
The first line contains two integers N, M, such as the title of the meanings (1 <= N, M < = 100000)
The second line contains N integers, N number of corresponding length of the rope (0 <l [i ] <10 ^ 9)
output description:
a number indicating the length of the longest cut, two decimal places
example 1
input:
. 3. 4
. 3. 5. 4
output:
2.50
explained: a first root and a third cut-out a piece of string, respectively, root 2.50 rope length, rope second just to cut out two 2.50 rope length, just four.

Problem-solving ideas

After cutting the length of each rope must be between 0 and Max (the original length of the cord), the requirements of the desired length using a binary search to find

Problem-solving Code

public class Main {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        //现有绳子的数量为n
        int n = sc.nextInt();
        //需要剪成m根绳子
        int m = sc.nextInt();
        //现在每根绳子的长度
        int[] length = new int[n];
        for(int i = 0;i < n;i++){
            length[i] = sc.nextInt();
        }
        //找到最长的那根绳子,截取后每根绳子的长度不可能大于它
        int max = length[0];
        for (int i = 1; i < n; i++) {
            if (max < length[i]) max = length[i];
        }
        //二分查找法
        double high = max;
        double low = 0;
        double mid = 0;
        //计算按照最大长度裁剪得到的绳子根数
        int count ;
        //1.0E-6是运算的精度
        while (high - low > 1.0E-6){
            mid = (low + high) / 2;
            count = checkMax(length, mid);
            //如果计算出的结果小于m,说明最大长度大了,
            if (count < m)
                high = mid;
            //如果计算出的结果大于m,说明最大长度小了,
            else
                low = mid;
        }
        System.out.println(String.format("%.2f",mid));
    }
    private static int checkMax(int[] a, double maxLength) {
        int count = 0;
        for (int i = 0; i < a.length; i++) {
            Double s = a[i] / maxLength;
            int s1 = s.intValue();
            count += s1;
        }
        return count;
    }

}

Guess you like

Origin blog.csdn.net/qq_40981804/article/details/89556812