Luo Gu P1182 series segmentation problem solution

Face questions

Give us a universal knowledge, you see the maximum or minimum maximum minimum think about it and so forth go out on a half!

Then a positive solution part:
   we can answer two points;
   for each binary interval intermediate value mid, and determines its Check ();
   may be divided into m segments if the maximum value of all the segments of mid (Note that if at this time into the segment is smaller than m, it is possible, because you can not be demolished demolition will be able to split into m sections, but apparently may not be optimal solution), then we will change the partition between the two (l, mid), because (mid + 1, r) range all the answers are feasible and are not optimal. Otherwise the interval to (mid + 1, r);  Stated otherwise, with the proviso that two exit points l == r, and recorded at this time is equal ans r.  Then output ans just fine
   

#include <bits/stdc++.h>
using namespace std;
int n,m;
int a[100010],sum[100010];
int ans;
bool check(int x)
{
    for(int i=1;i<=n;i++){
        if(sum[i]-sum[i-1]>x){
            return 0;
        }
    }
    int tmp=0;
    int cnt=0;
    for(int i=1;i<=n;i++){
        if(sum[i]-tmp>x){
            tmp=sum[i-1];
            ++cnt;
            i--;
        }
    }
    if(cnt+1>m)  return 0;
    return 1;
}
void erfen(int l,int r)
{
    if(l==r){
        ans=l;
        return;
    }
    int mid=(l+r)/2;
    if(check(mid)) erfen(l,mid);
    else erfen(mid+1,r);
}
int main ()
{    
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++){
        scanf("%d",&a[i]);
        sum[i]=sum[i-1]+a[i];
    }
    erfen(1,sum[n]);
    cout<<ans;
}

 

Guess you like

Origin www.cnblogs.com/kamimxr/p/11319249.html