leetcode 1011. 在 D 天内送达包裹的能力

抽象为把序列分成D段,求和最大的段的最小值

下界为最大值,上界为序列和,二分结果,每次去验证是否合适即可

class Solution {
public:

    int shipWithinDays(vector<int>& weights, int D) {
        int total = 0;
        int max_v = weights[0];
        for(int i = 0; i < weights.size(); i++) max_v = max(max_v, weights[i]), total += weights[i];
        int x = max_v, y = total;
        int cnt = 1, cnt_s;
        while(x < y)
        {
            cnt_s = 0;
            cnt = 1;
            int mid = (x + y) / 2;
            int i;
            for(i = 0; i < weights.size(); i++)
                if(cnt_s + weights[i] <= mid) cnt_s += weights[i];
                else cnt_s = weights[i], cnt++; 
            if(cnt > D) x = mid + 1;
            else y = mid;
        }
        return x;


    }
};

 

上一篇:Docker 安装 oracle11


下一篇:noi题库1011. 正方形