二分法解最小化【数组分段和】问题

  • LCP 12. 小张刷题计划
class Solution {
public:
    int getNum(vector<int>& time, int vol) {
        int res = 1;
        int Sum = 0;
        int Max = 0;
        for (int i = 0; i < time.size(); i++) {
            if (time[i] > Max) {
                Sum += Max;
                Max = time[i];
            }
            else {
                Sum += time[i];
            }
            if (Sum > vol) {
                res++;
                Sum = 0;
                Max = time[i];
            }
        }
        return res;
    }
    
    int minTime(vector<int>& time, int m) {
        int n = time.size();
        if (!n) {
            return 0;
        }
        int Sum = 0;
        int Max = 0;
        for (int i = 0; i < n; i++) {
            Sum += time[i];
            Max = max(Max, time[i]);
        }
        int low = 0;
        int high = Sum - Max;
        while (low < high) {
            int mid = (low + high) / 2;
            int res = getNum(time, mid);
            if (res > m) {
                low = mid + 1;
            }
            else {
                high = mid;
            }
        }
        return low;
    }
};

References

  1. 数组分段和最大值最小问题

你可能感兴趣的:(ACM)