洛谷 P1182 二分

洛谷 P1182

二分 前缀和 贪心

#include <bits/stdc++.h>
using namespace std;
int n,m,a[100010],l,r,mid,ans;
inline bool check(int x)
{
    int tot=0,num=0;
    for (int i = 1; i <= n; i++)
    {
        if (tot+a[i] <= x)
        {
            tot += a[i];
        }
        else
        {
            tot = a[i];
            num++;
        }
        
    }
    return num >= m;
}

int main()
{
    scanf("%d%d", &n, &m);
    for (int i = 1; i <= n; i++)
    {
        scanf("%d", &a[i]);
        l = max(l,a[i]);
        r += a[i];
    }
    while (l <= r)
    {
        mid = l+r>>1;
        if(check(mid))
        {
            l = mid + 1;
        }
        else
        {
            r = mid - 1;
        }
    }
    cout << l;
    system("pause");
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/lil-laian/p/12296837.html
今日推荐