1436: the number of columns segment II
answer
Dichotomous answer
Our final answer is the value interval [max (a [i]), Σa [i]]
Setting l = max (a [i]), r = Σa [i], mid continuously bipartite
mid represents the maximum value and each segment, that is, each segment and not more than mid
Lane into the check function, calculate the maximum value in the case of mid section may be divided into a number
If the number of segments cnt> m, illustrate the mid small, it can be slightly larger
If the number of segments cnt <= m, illustrate the mid big, then it will a little, because at this time cnt may be equal to m, this mid candidate answers recorded (if he is the real answer, the final output is that he, otherwise he will be updated to a smaller)
Code
#include<iostream> #include<cstdio> #include<algorithm> #include<cmath> #include<cstring> #include<string> #include<queue> #include<functional> using namespace std; int n,m,ans,l=0,r=0; int a[100001]; int sum[100001]; int check(int x) { int cnt=1,now=0; for(int i=1;i<=n;i++) { if(now+a[i]<=x) now+=a[i]; else { cnt++; now=a[i]; } } 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) { int mid=(r+l)/2; if(check(mid)) { ans=mid; r=mid-1; } else l=mid+1; } printf("%d",ans); }