Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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;
    }
};

 

posted on 2015-10-07 11:47  Tonix  阅读(226)  评论(0编辑  收藏  举报