二分答案—洛谷P1182 数列分段`Section II`

简单的二分答案,但要注意边界的选取以及如何二分答案

#include<bits/stdc++.h>
using namespace std;
const int maxn=1e6+7;
int n,m;
int a[maxn];
int sum[maxn];bool check(int x)//判断当前的答案
{
    int cnt=0;
    int tot=0;
    for(int i=1;i<=n;i++)
    {
        if(tot+a[i]<=x)
        {
            tot+=a[i];
        }
        else
        {
            tot=a[i];
            cnt++;
        }
    }
    return cnt>=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)//二分模板(因题而异,不过与zbh上课讲的不太一样)
    {
        int mid=(l+r)>>1;
        if(check(mid))    l=mid+1;
        else    r=mid-1;
    }
    printf("%d",l);//答案是最大的最小,所以在左边界
    return 0;
}

 

posted @ 2019-06-07 13:34  JBLee  阅读(146)  评论(0编辑  收藏  举报