LintCode "Wood Cut"

Binary search. Please not data types and some details.

class Solution {
public:
    /**
     *@param L: Given n pieces of wood with length L[i]
     *@param k: An integer
     *return: The maximum length of the small pieces.
     */
    int woodCut(vector<int> L, int k)
    {
        long long sum = 0;
        for(auto v : L) sum += v;
        if(sum < k) return 0;
        
        long long a = 0, b = *max_element(L.begin(), L.end());
        long long ret = a;
        while(a <= b)
        {
            long long m = (a + b) / 2;

            long long mk = 0;
            for(auto l : L) mk += l / m;
            
            if(mk < k)
            {
                b = m - 1;
            }
            else if (mk >= k)
            {
                ret = max(ret, m);
                a = m + 1;
            }
        }
        return ret;
    }
};
原文地址:https://www.cnblogs.com/tonix/p/4858457.html