from sortedcontainers import SortedList as MonoQueue
class Solution:
    def boxDelivering(self, A, __, B, W):
        n = len(A)
        def slidingWindow():
            l=0
            cW = 0
            for r in range(n):
                cW+=A[r][1]
                while cW>W or r-l+1>B:
                    cW-=A[l][1]
                    l+=1
                yield l,r
        Seg=MonoQueue(key=lambda t:t[1])
        addAll = 0
        olddp = 0
        for l,r in slidingWindow():
            if r!=0:
                addAll+= ( A[r][0]!=A[r-1][0] )
            Seg.add((r, olddp-addAll+2))
            while Seg[0][0]<l:
                Seg.pop(0)
            olddp = Seg[0][1]+addAll
        return olddp
class Solution {
    public int boxDelivering(int[][] boxes, int portsCount, int maxBoxes, int maxWeight) {
        int[] diffCity = new int[boxes.length+1];
        int[] weights = new int[boxes.length+1];
        
        for (int i = 0; i < boxes.length; i++) {
            diffCity[i+1] = diffCity[i] + ((i != 0 && boxes[i][0] == boxes[i-1][0]) ? 0 : 1);
            weights[i+1] = weights[i] + boxes[i][1];
        }
        int[] dp = new int[boxes.length+1];
        Arrays.fill(dp, Integer.MAX_VALUE);
        dp[0] = 0;
        diffCity[0] = 1;
        for (int i = 1; i <= boxes.length; i++) { // offset by 1 since our above logic reaches dp[-1]
            for (int j = i - 1; j >= 0; j--) {
                int dC= diffCity[i] - diffCity[j+1]; // computes # of different cities from i to j. (add 1 to j is necessary here)
                int w = weights[i] - weights[j]; 
                int b = i - j;
                if (b <= maxBoxes && w <= maxWeight) {
                    dp[i] = Math.min(dp[i], 2 + dC + dp[j]); 
                }
            }
        }
        return dp[boxes.length];
    }
}
Delivering Boxes from Storage to Ports
You have the task of delivering some boxes from storage to their ports using only one ship. However, this ship has a limit on the number of boxes and the total weight that it can carry.

You are given an array boxes, where boxes[i] = [ports​​i​, weighti], and three integers portsCount, maxBoxes, and maxWeight.


	ports​​i is the port where you need to deliver the ith box and weightsi is the weight of the ith box.
	portsCount is the number of ports.
	maxBoxes and maxWeight are the respective box and weight limits of the ship.


The boxes need to be delivered in the order they are given. The ship will follow these steps:


	The ship will take some number of boxes from the boxes queue, not violating the maxBoxes and maxWeight constraints.
	For each loaded box in order, the ship will make a trip to the port the box needs to be delivered to and deliver it. If the ship is already at the correct port, no trip is needed, and the box can immediately be delivered.
	The ship then makes a return trip to storage to take more boxes from the queue.


The ship must end at storage after all the boxes have been delivered.

Return the minimum number of trips the ship needs to make to deliver all boxes to their respective ports.

&nbsp;
Example 1:

Input: boxes = [[1,1],[2,1],[1,1]], portsCount = 2, maxBoxes = 3, maxWeight = 3
Output: 4
Explanation: The optimal strategy is as follows: 
- The ship takes all the boxes in the queue, goes to port 1, then port 2, then port 1 again, then returns to storage. 4 trips.
So the total number of trips is 4.
Note that the first and third boxes cannot be delivered together because the boxes need to be delivered in order (i.e. the second box needs to be delivered at port 2 before the third box).


Example 2:

Input: boxes = [[1,2],[3,3],[3,1],[3,1],[2,4]], portsCount = 3, maxBoxes = 3, maxWeight = 6
Output: 6
Explanation: The optimal strategy is as follows: 
- The ship takes the first box, goes to port 1, then returns to storage. 2 trips.
- The ship takes the second, third and fourth boxes, goes to port 3, then returns to storage. 2 trips.
- The ship takes the fifth box, goes to port 3, then returns to storage. 2 trips.
So the total number of trips is 2 + 2 + 2 = 6.


Example 3:

Input: boxes = [[1,4],[1,2],[2,1],[2,1],[3,2],[3,4]], portsCount = 3, maxBoxes = 6, maxWeight = 7
Output: 6
Explanation: The optimal strategy is as follows:
- The ship takes the first and second boxes, goes to port 1, then returns to storage. 2 trips.
- The ship takes the third and fourth boxes, goes to port 2, then returns to storage. 2 trips.
- The ship takes the fifth and sixth boxes, goes to port 3, then returns to storage. 2 trips.
So the total number of trips is 2 + 2 + 2 = 6.


&nbsp;
Constraints:


	1 &lt;= boxes.length &lt;= 105
	1 &lt;= portsCount, maxBoxes, maxWeight &lt;= 105
	1 &lt;= ports​​i &lt;= portsCount
	1 &lt;= weightsi &lt;= maxWeight


/**
 * @param {number[][]} boxes
 * @param {number} portsCount
 * @param {number} maxBoxes
 * @param {number} maxWeight
 * @return {number}
 */
var boxDelivering = function(boxes, portsCount, maxBoxes, maxWeight) {

    const trips = Array(boxes.length + 1).fill(0);
    let left = 0;
    let diff = 0;

    for (let right = 0; right < boxes.length; right++) {
        maxBoxes--;
        maxWeight -= boxes[right][1];
        if (right > 0 && boxes[right][0] !== boxes[right - 1][0]) diff++;

        while (maxBoxes < 0 || maxWeight < 0 || (left < right && trips[left + 1] === trips[left])) {
            maxBoxes++;
            maxWeight += boxes[left++][1];
            if (boxes[left][0] !== boxes[left - 1][0]) diff--;
        }

        trips[right + 1] = diff + 2 + trips[left];
    }

    return trips[boxes.length];
};
class Solution {
public:
    vector<int> stree;
    void update(int tidx, int s, int e, int idx, int val){
        if(s == e){
            stree[tidx] = val;
            return;
        }
        int mid = (s + e)/2;
        if(idx <= mid) update(2*tidx, s, mid, idx, val);
        else update(2*tidx+1, mid+1, e, idx, val);
        stree[tidx] = min(stree[2*tidx], stree[2*tidx+1]);
    }
    int query(int tidx, int s, int e, int l, int r){
        if(s > r or e < l) return INT_MAX;
        else if(s >= l and e <= r) return stree[tidx];
        int mid = (s + e)/2;
        int left = query(2*tidx, s, mid, l, r);
        int right = query(2*tidx+1, mid+1, e, l, r);
        return min(left, right);
    }
    int boxDelivering(vector<vector<int>>& boxes, int port, int box, int weigh) {
        int n = boxes.size();
        vector<long long> trips(n+1), pref(n);
        trips[0] = 0, pref[0] = boxes[0][1];
        for(int i=1;i<n;i++){
            pref[i] = pref[i-1] + boxes[i][1];
            if(boxes[i][0] != boxes[i-1][0]){
                trips[i] = trips[i-1] + 1;
            }
            else{
                trips[i] = trips[i-1];
            }
        }
        trips[n] = trips[n-1];
        vector<long long> dp(n);
        stree = vector<int> (4*n + 1, INT_MAX);
        update(1, 0, n-1, 0, 0);
        // dp[i] = dp[j] + (trips[i] - trips[j+1]) + 2
        for(int i=0;i<n;i++){
            // L nikalo ?
            int l = 0, r = i;
            while(l < r){
                int mid = (l + r)/2;
                long long tot = pref[i] - ((mid-1>=0)?pref[mid-1]:0);
                if(tot <= weigh and i-mid+1 <= box){
                    r = mid;
                }
                else{
                    l = mid + 1;
                }
            }
            int mini = query(1, 0, n, l, i);
            dp[i] = mini + trips[i] + 2;
            update(1, 0, n, i+1, dp[i] - trips[i+1]);
        }
        return dp[n-1];
    }
};