真的说是算法博大精深啊!看了这道题后,我先想到的是动态规划,然后是深搜,然后都没有思路写出来,后来看了别人的解析然后然后才明白过来,以前都只把二分法当作排序了,看来以后要多做题,多扩展思路!
这道题和3258有一拼!
#include<iostream>
using namespace std;
int n,m,a[100005];
int fun(int mid)
{
int i,count=1,s=0;
for(i=1; i<=n; i++)
{
if(s+a[i]<=mid)
s+=a[i];
else
{
count++;//份数加1
s=a[i];
}
}
if(count>m)
return 1;
else
return 0;
}
int main()
{
int low,high,i,mid;
while(scanf("%d%d",&n,&m)!=EOF)
{
high=0;
low=0;
for(i=1; i<=n; i++)
{
scanf("%d",&a[i]);
high+=a[i];
if(a[i]>low)
low=a[i];
}
while(low<=high)
{
mid=(low+high)/2;
if(fun(mid))
low=mid+1;
else
high=mid-1;
}
printf("%d\n",low);
}
return 0;
}