理工学院的枇杷快熟了,ok,大家都懂得。而且大家都知道,学校的枇杷树都是一列一列的。现在小Y同学已经在筹划怎么摘枇杷了。现在我们假设有一列枇杷树,而且每棵枇杷树上枇杷果的数量小Y都已经知道了。
假设现在有n棵枇杷树,小Y可以把这n棵枇杷树分成m组,每组枇杷果的数量是这组内每棵枇杷树上枇杷果数量的和。注意,每组的枇杷树必须是连续的。(每组最少1棵树,最多n棵树)。小Y把枇杷往寝室拿的时候是一组一组拿的,所花费的力气等于这m组中枇杷果最多的那组枇杷果的数量。现在小Y想花尽量少的力气把这些枇杷果拿回寝室。
3 2 1 2 3 7 5 1 4 3 1 5 2 4
3 5
这是一个最大值最小化的问题。二分枚举最终答案即可。
#include<stdio.h>
#include<algorithm>
using namespace std;
const int N = 1005;
int a[N], Max, sum, n, m;
bool judge(int x)
{
    int s = 0, cnt = 0;
    for(int i = 0; i < n; i++)
    {
        if(a[i] > x)
            return false;
        if(s + a[i] > x)
        {
            cnt++;
            s = a[i];
            if(cnt > m - 1)
                return false;
        }
        else
            s += a[i];
    }
    return true;
}
int get_ans()
{
    int l = Max, r = sum;
    while(l <= r)
    {
        int mid = (l + r) / 2;
        if(judge(mid))
            r = mid - 1;
        else
            l = mid + 1;
    }
    return l;
}
int main()
{
    while(~scanf("%d%d",&n,&m))
    {
        sum = 0, Max = 0;
        for(int i = 0; i < n; i++)
        {
            scanf("%d",&a[i]);
            sum += a[i];
            Max = max(Max, a[i]);
        }
        printf("%d\n",get_ans());
    }
    return 0;
}NYOJ 680 摘枇杷(二分搜索+贪心),布布扣,bubuko.com
原文:http://blog.csdn.net/lyhvoyage/article/details/23263275