Problem Summary
Given N boards and R rails and their lengths, find the maximal number of wanted rails that can be cut from the given boards.
Solution
This is a multiple knapsack problem. Due to the high dimensionality, the search tree is huge, which made me think about using IDDFS (iterative deepening depth first search with iterative deepening) to limit the depth.
Then I combined IDDFS with binary search to make the search faster. That is , instead of traversing through all possible numbers, I use binary search to find the maximal number, and for each middle number, use DFS to determine if it is achievable.
After this, the search is still huge work, so I found a few ways to prune the search tree:
If a rail has greater length than all boards, then there is no need to consider it.
The range of each rail’s length is from 1 to 128, but R can be at most 1023. So there can be many rails of the same length. For any two rails with the same length, we can cut them from boards of non-decreasing index.
If there is a board of the same length of the rail, then cutting that rail from that board is optimal.
If there is a way to cut k rails, there is a way to cut the k shortest rails, so we only consider the k shortest rails.
We can stop searching if it finds a way to cut the largest set of shortest rails such that the sum of the lengths of the rails waiting is greater than the sum of the left board lengths.
Besides, the search can get even faster if we add some greedy algorithm. We can sort the boards by length, and do the same for the rails. And for each time we start searching, we search from the rail with greatest length and try to cut from the board with least length.
Code
|
|