lightoj 1076 【二分找满足条件的最左】

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int,int>PII;
const double eps=1e-5;
const double pi=acos(-1.0);
const int INF=0x3f3f3f3f;

const int N=1e3+10;
int a[N];
int n,k;

bool Judge(int w)
{
    int num=1;
    int sum=a[1];
    for(int i=2;i<=n;i++)
    {
        if(sum+a[i]<=w)
            sum+=a[i];
        else
        {
            sum=a[i];
            num++;
        }
        if(num>k)
            return false;
    }
    return true;
}

int binary_find(int left,int right)
{
    int mid;
    while(left<right)
    {
        mid=left+(right-left)/2;
        if(Judge(mid))
            right=mid;
        else
            left=mid+1;
    }
    return left;
}

int main()
{
    int T,cas=1;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d%d",&n,&k);
        int t=0;
        int s=0;
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&a[i]);
            s=max(a[i],s);
            t+=a[i];
        }
        printf("Case %d: %d
",cas++,binary_find(s,t));
    }
    return 0;
}

原文地址:https://www.cnblogs.com/keyboarder-zsq/p/6777516.html