Description:
对于给定的一个长度为N的正整数数列A-i,现要将其分成M(M≤N)段,并要求每段连续,且每段和的最大值最小。
Anakysis:
二分的边界还是不明白
Code
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int MAX_N = 100100;
int a[MAX_N],lb,ub,n,m;
bool C(int x)
{
int cnt = 0,lastSum = 0;
for(int i = 1;i <= n;++i)
{
if(lastSum + a[i] <= x) lastSum += a[i];
else lastSum = a[i],cnt++;
}
if(cnt >= m) return 1;
else return 0;
}
void solve()
{
int mid;
while(lb <= ub)
{
mid = (lb + ub) / 2;
if(C(mid)) lb = mid + 1;
else ub = mid - 1;
}
printf("%d
",lb);
}
int main()
{
scanf("%d%d",&n,&m);
for (int i = 1;i <= n;++i)
{
scanf("%d",&a[i]);
ub += a[i];
lb = max(lb,a[i]);
}
solve();
return 0;
}