题目地址:http://poj.org/problem?id=3273
思路:二分最小值x(1--sum{a[i]})。从小到大依次相加,判断当前数量是否大于x,若大于则num++,最终若num不大于m,则该x可行。
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn=1e5+50;
int n,m;
int a[maxn];
int check(int x)
{
int num=0;
for(int i=1,j;i<=n;i=j+1)
{
j=i,num++;
int tmp=a[j];
if(a[i]>x) return 0;
while(j+1<=n&&tmp+a[j+1]<=x)
{
if(a[j]>x) return 0;
tmp+=a[j+1],j++;
}
}
return num<=m;
}
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
int sum=0;
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
sum+=a[i];
}
int l=0,r=sum,ans;
while(l<=r)
{
int mid=(l+r)>>1;
if(check(mid))
{
ans=mid;
r=mid-1;
}
else
{
l=mid+1;
}
}
printf("%d\n",ans);
}
return 0;
}