问题:
传送带上的包裹必须在 D 天内从一个港口运送到另一个港口。
传送带上的第 i 个包裹的重量为 weights[i]。每一天,我们都会按给出重量的顺序往传送带上装载包裹。我们装载的重量不会超过船的最大运载重量。
返回能在 D 天内将传送带上的所有包裹送达的船的最低运载能力
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/capacity-to-ship-packages-within-d-days
解题思路:
- 船的最低运载能力必然在(max(weights[i]),sum(weights[i])之间,而且是单调的,所以最简单的方法是枚举,为提高效率,采用二分查找;
- 如何判断船的运载能力n,能否在D 天内将传送带上的所有包裹送达:首先对于每艘船采用贪心策略装到装不下为止;可以对货物进行遍历,得到运送完货物需要的天数,假如不大于D,表明满足要求
代码:
class Solution {
public static int shipWithinDays(int[] weights, int D) {
int lo=1;
int hi=500;
int mid=0;
int w=0;
for (int weight:weights){
w +=weight;
}
mid=w;
while(lo<hi){
if(canShip(weights,D,mid)){
hi=mid;
}
else{
lo=mid+1;
}
mid=(lo+hi)/2;
}
return mid;
}
public static boolean canShip(int [] weights,int D,int w){
int i;
int cur =w;
for (i=0;i<weights.length;i++){
if(weights[i]>w)
return false;
if(cur<weights[i]){
D--;
cur =w;
}
cur -=weights[i];
if (D<=0){
break;
}
}
return i==weights.length;
}
public static void main(String [] args){
int [] weights={1,2,3,4,5,6,7,8,9,10};
//boolean t=canShip(weights, 5, 14);
//System.out.println(t);
int minw=shipWithinDays(weights,5);
System.out.println(minw);
}
}