链接:点击打开链接
题意:给出N个数,分成M部分(不能调换顺序),使得分成的M部分中和的最大值最小
代码:
#include <cstdio>
#include <iostream>
using namespace std;
const int INF=0x3f3f3f3f;
int N,M;
int x[1000005];
int judge(int d){
int i,sum,cou;
sum=cou=0;
for(i=0;i<N;i++){
sum+=x[i];
if(sum>d){
cou++;
sum=x[i];
}
}
if(sum!=0)
return cou+1;
return cou;
} //最大值是d时能分成几部分
int main(){
int i,j,l,r,mid,sum,ans;
while(scanf("%d%d",&N,&M)!=EOF){
l=sum=0;
for(i=0;i<N;i++){
scanf("%d",&x[i]);
sum+=x[i];
l=max(l,x[i]);
}
r=sum;
while(l<=r){ //二分 最小化最大值
mid=(l+r)/2;
// cout<<l<<" "<<r<<" "<<mid<<" "<<judge(mid)<<endl;
if(judge(mid)<=M){
ans=mid;
r=mid-1;
}
else
l=mid+1;
}
printf("%d\n",ans);
}
return 0;
}