二分出一个货运量,判断其是否能在规定的天数内完成所有货物的装载工作。
class Solution {
public:
int shipWithinDays(vector<int>& weights, int D) {
int l=0,r=1e9;
while(l<r)
{
int mid=(l+r)>>1;
int co=1,temp=0,f=0; //co:初始天数为1,temp:当前装载的总量,f:是否能完成任务
for(auto x:weights) //遍历每个物品
{
if(x>mid){ //如果当前物品大于枚举的装载量,直接不能完成任务,break
f=1;
break;
}
temp+=x;
if(temp>mid) //当前已经装满了
{
co++; //天数co++
temp=x;
}
if(co>D) //如果总天数大于规定的天数D,说明任务不能完成,退出
{
f=1;
break;
}
}
if(!f) r=mid; //任务完成,缩小范围继续二分
else l=mid+1;
}
return l;
}
};