1011. Capacity To Ship Packages Within D Days

问题:

传送带依次传送weights数组上对应元素重量的货物。

限制每天最多传送X重量的货物,D天刚好传送完毕,请问这个限重X是多少。

Example 1:
Input: weights = [1,2,3,4,5,6,7,8,9,10], D = 5
Output: 15
Explanation: 
A ship capacity of 15 is the minimum to ship all the packages in 5 days like this:
1st day: 1, 2, 3, 4, 5
2nd day: 6, 7
3rd day: 8
4th day: 9
5th day: 10

Note that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed. 


Example 2:
Input: weights = [3,2,2,4,1,4], D = 3
Output: 6
Explanation: 
A ship capacity of 6 is the minimum to ship all the packages in 3 days like this:
1st day: 3, 2
2nd day: 2, 4
3rd day: 1, 4

Example 3:
Input: weights = [1,2,3,1,1], D = 4
Output: 3
Explanation: 
1st day: 1
2nd day: 2
3rd day: 3
4th day: 1, 1
 

Note:
1 <= D <= weights.length <= 50000
1 <= weights[i] <= 500

 

解法:

二分查找:最合适的每日限重。

这个限重的范围:

最小值l:最小一天只运送一件货物,所有货物中的最大重量的那一件货物也能被运送。max(weights[i])

最大值h:一天送完所有货物,所有货物总量之和。sum(weights[..])

找最大最小值之间,最合适的限重,使得:

每天都有货物可送,且连续送D天。

尝试中,

若送的days天数>D天,那么调整【扩大】每天最多送的量 l->mid+1

若送的days天数<=D天,那么调整【缩小】每天最多送的量 h->mid

 

代码参考:

 1 class Solution {
 2 public:
 3     int shipWithinDays(vector<int>& weights, int D) {
 4         int l=0, h=0;
 5         int n=weights.size();
 6         for(int w:weights){
 7             h+=w;
 8             l=max(l, w);
 9         }
10         while(l<h){
11             int mid=(l+h)/2;
12             int cur=0, days=1;
13             for(int w:weights){
14                 if(cur+w > mid){
15                     days++;
16                     cur=0;
17                 }
18                 cur+=w;
19             }
20             if(days>D) l=mid+1;
21             else h=mid;
22         }
23         return l;
24     }
25 };

 

posted @ 2020-06-02 11:36  habibah_chang  阅读(157)  评论(0编辑  收藏  举报