P1182 数列分段`Section II`

P1182 数列分段`Section II`

二分答案

初始设l=0,r=1e9

然后二分答案,每次在数列中跑一遍判断是否合法即可。

复杂度 O(n log1e9)

(真的要改掉我不检查就交的坏习惯qaq)

#include<cstdio>
#include<cstring>
#include<cctype>
using namespace std;
inline int Int(){
    char c=getchar(); int x=0;
    while(!isdigit(c)) c=getchar();
    while(isdigit(c)) x=(x<<3)+(x<<1)+(c^48),c=getchar();
    return x;
}
int n,m,a[100002];
int main(){
    n=Int(); m=Int();
    for(int i=1;i<=n;++i) a[i]=Int();
    int l=0,r=1e9,mid,cnt,p; bool ok;
    while(l<r){
        mid=l+((r-l)>>1),cnt=1,p=0; ok=1;
        for(int i=1;i<=n;++i){
            if(p+a[i]>mid) ++cnt,p=a[i];
            else p+=a[i];
            if(cnt>m||a[i]>mid) {ok=0; break;} //不合法就跳出
        }
        if(!ok) l=mid+1;
        else r=mid;
    }
    printf("%d",l);
    return 0;
}
原文地址:https://www.cnblogs.com/kafuuchino/p/9571757.html