这道题目是考虑的最多的一个。
因为牵扯到最后一箱子该咋发的问题。
题意: 传送带上有N个包裹(包裹顺序是没有办法调整的), 要通过海运运出去。
给了要在多少天之内全部送出去。
求运的船的大小。
我的天哪,这难道是个船运公司出的题目吗?
画图画图画图
capacity/ship 1 2 3 4 5 6 7 8
weights
1 1 1 1 1 1 1 1 1
2 x 1 3 3 3 3 3 3
3 x x 3 3 3 3 6 6
1 1 0.5 1 4 4 4 7 7
1 1 0.5 2 1 5 5 1 8
days 3 3 2 2 2 1
binary search for the capacity/ship
start = max of weights/package such as 3 (can not ship the package if capacity is less than the package weight)
end = sum of weights(the big ship which can carry all the packages at one time)
caclDaysWithCapacity 函数的大概功能
if sumOfWeight < capacity => continue;
if sumOfWeight == capacity => ship it -> days + 1
if sumOfWeight > capacity =>ship it -> days + 1 => remove the last package from this ship and put it for the next ship
sumOfWeight = lastWeight;
我觉得我已经蛮清楚了,但是还是败给了细节。 当到了最后一个包裹的时候,咋处理。提交了4次才通过。
代码如下。
class Solution {
public:
int calcDaysWithShipCapacity(int capacity, vector<int>& weights) {
long sumOfWeight = 0;
int days = 0;
for(int i = 0;i < weights.size(); i++) {
sumOfWeight += weights[i];
if(sumOfWeight < capacity) {
if(i != weights.size() - 1)
continue;
else
days++; // last package need to special handle => ship it =>days + 1
}
else if(sumOfWeight == capacity) {
days++;
sumOfWeight = 0;
}
else if(sumOfWeight > capacity) {// if sumOfWeight > capacity =>ship it -> days + 1 => remove the last package from this ship and put it for the next ship
days++;
sumOfWeight = weights[i];
if(i == weights.size() - 1) // last package need to special handle => ship it =>days + 1
days++;
}
}
return days;
}
int shipWithinDays(vector<int>& weights, int days) {
//画图画图画图
//capacity/ship 1 2 3 4 5 6 7 8
//weights
// 1 1 1 1 1 1 1 1 1
// 2 x 1 3 3 3 3 3 3
// 3 x x 3 3 3 3 6 6
// 1 1 0.5 1 4 4 4 7 7
// 1 1 0.5 2 1 5 5 1 8
//days 3 3 2 2 2 1
// binary search for the capacity/ship
// start = max of weights/package such as 3 (can not ship the package if capacity is less than the package weight)
// end = sum of weights(the big ship which can carry all the packages at one time)
// caclDaysWithCapacity
// if sumOfWeight < capacity => continue;
// if sumOfWeight == capacity => ship it -> days + 1
// if sumOfWeight > capacity =>ship it -> days + 1 => remove the last package from this ship and put it for the next ship
// sumOfWeight = lastWeight;
int start = 1, end = 0;
for(int weight: weights) {
start = max(start,weight);
end += weight;
}
while(start + 1 < end) {
int mid = start + (end - start) / 2;
int needDays = calcDaysWithShipCapacity(mid, weights);
if(needDays > days)
start = mid;
else
end = mid;
}
if(calcDaysWithShipCapacity(start, weights) <= days)
return start;
if(calcDaysWithShipCapacity(end, weights) <= days)
return end;
return -1;
}
};