zoukankan      html  css  js  c++  java
  • leetcode_1011. Capacity To Ship Packages Within D Days_binary search二分

    https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/

    传送带每天有最大传送量V,对于n个货物[w1,w2,w3...wn],要在D天内将所有货物传送完的V最小为多少?

    二分每天最大传送量V,初始:Vhigh = sum(w),Vlow = max(w)。

    class Solution
    {
    public:
        int calc_days(vector<int>& weights, int V)
        {
            int len = weights.size(), days=0, i=0, cur=0;
            while(i<len)
            {
                if(cur+weights[i] > V)
                {
                    days++;
                    cur=0;
                }
                cur += weights[i++];
            }
            if(cur>0)
                days++;
            return days;
        }
    
        int shipWithinDays(vector<int>& weights, int D)
        {
            int high=0, lenw=weights.size(), low=0;
            for(int i=0; i<lenw; i++)
            {
                high += weights[i];
                low = max(low, weights[i]);
            }
            int res=0;
            while(low<=high)
            {
                int mid = (high+low)>>1;
                if(D >= calc_days(weights, mid))
                {
                    high = mid-1;
                    res = mid;
                }
                else
                    low = mid+1;
            }
            return res;
        }
    };
  • 相关阅读:
    2-7
    2-6
    2-5
    2-4
    2-3
    2-1
    2-2
    1-1
    5-7
    第六章例6-1
  • 原文地址:https://www.cnblogs.com/jasonlixuetao/p/10696117.html
Copyright © 2011-2022 走看看