【最短木板长度】

 

题目描述

【最短木板长度】

小明有 n 块木板,第 i ( 1 ≤ i ≤ n ) 块木板长度为 ai。
小明买了一块长度为 m 的木料,这块木料可以切割成任意块,
拼接到已有的木板上,用来加长木板。
小明想让最短的模板尽量长。
请问小明加长木板后,最短木板的长度可以为多少?

流程分析:
1. 只有一个板子的时候直接加;
2. 超过2个板子
    从最小阶级差开始,一层一层计算:
        可能一根都补不齐;
        可能满足一部分;
        可能补到当前最高板子还多;

import java.util.*;

public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();
        int[] a = new int[n];
        for (int i = 0; i < n; i++) {
            a[i] = sc.nextInt();
        }

        if (n == 1) {
            System.out.println(a[0] + m);
        } else {
            HashSet<Integer> hashSet = new HashSet<>();
            HashMap<Integer, Integer> map = new HashMap<>();
            for (int i = 0; i < a.length; i++) {
                hashSet.add(a[i]);

                if (map.containsKey(a[i])) {
                    map.put(a[i], map.get(a[i]) + 1);
                } else {
                    map.put(a[i], 1);
                }
            }
            ArrayList<Integer> list = new ArrayList<>(hashSet);
            Collections.sort(list);
            int minLength = list.get(0);
            for (int i = 0; i < list.size(); i++) {
                if (i == list.size() - 1) {
                    int avr = m / a.length;
                    if (avr > 0) {
                        minLength += avr;
                    }
                    break;
                }
                int num = list.get(i + 1) - list.get(i);
                if (m >= num * map.get(list.get(i))) {
                    m -= num * map.get(list.get(i));
                    map.put(list.get(i + 1), map.get(list.get(i + 1)) + map.get(list.get(i)));
                    minLength = list.get(i + 1);
                } else {
                    int avr = m / map.get(list.get(i));
                    if (avr != 0) {
                        minLength = list.get(i) + avr;
                    } else {
                        minLength = list.get(i);
                    }
                    break;
                }
            }
            System.out.println(minLength);
        }
    }
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值