
- portsi 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 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 must end at storage after all the boxes have been delivered.
Remember that the given list of boxes is to be delivered in the given order in the original box list.
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).
The first line of input is the number of test cases ‘T’ which are going to be there.
The first line of each test case would be three space-separated integers representing the ‘portsCount’, ‘maxBoxes’, and ‘maxWeight’.
The second line of each test case would an integer ‘N’ denoting the total number of boxes given which are needed to be delivered.
Now each ‘N’ line of the test case would comprise of two space-separated integers ‘port[i]’ and ‘weight[i]’.
For each test case, print a single line containing a single integer denoting the minimum number of trips the ship needs to make to deliver all boxes to their respective ports.
The output for every test case will be printed in a separate line.
You don’t need to print anything; It has already been taken care of. Just implement the function.
1 <= T <= 5
1 <= boxes.length <= 10 ^ 5
1 <= portsCount, maxBoxes, maxWeight <= 10 ^ 5
1 <= portsi <= portsCount
1 <= weightsi <= maxWeight
Where ‘boxes’ is the 2-D array of [‘portsi’,’ weights’], ‘portsCount’ is the number of ports, maxBoxes, and maxWeight is the respective box and weight limits of the ship.
Time Limit: 1 sec
The main idea here is to know that this is one typical structure of dynamic programming. We iterate through every box as if it's the last box, and calculate the minimal cost of shipping all of them. In each iteration, cost of the last trip is certain (depend on the type of the end division of it), so we just need to find the minimal cost of previous trips while the last trip is still within limiation.
The algorithm will be-