USACO 2019 US Open Contest, Gold Problem 1- Snakes
Problem Link
Algorithm Used: Dynamic Programming
Time Complexity: O(N³)
There are N groups of snakes given, of varying sizes. Nets are used to catch the snakes. Each net must be at least the size of the group of snakes being caught. Every time a group of snakes is caught, the space wasted is the difference in the size of the net and the size of the current group of snakes. To minimize the total amount of wasted space, the net size may be changed up to K times. Find the minimum total space that must be wasted in order to catch all the snakes.
At first glance, the way the nets are changed doesn't seem to follow any specific pattern that leads to a greedy/binary search/sorting solution, so the only other option is brute force. There are N groups of snakes and nets may be changed N times so there are N² possible states. For each state, the net size must be calculated by scanning the groups of snakes, so that a net that is smaller than the current group of snakes is not chosen. Then, computing the wasted space for each state takes O(N) time. The resulting time complexity of this approach is O(N⁴), which is too slow. Dynamic Programming can be used to speed up the brute force approach.
Instead of calculating wasted space to catch the ith group of snakes, we calculate the sum of net sizes used to catch the ith group of snakes, and then subtract the sum of snake group sizes from the sum of net sizes to find out the wasted space.
Compute the sum of net sizes used till the ith group of snakes, using j net size changes. This value will be stored in dp[i][j]. If the net is changed, then it may be changed at the ith group of snakes, or at any group before i, wherever the sum of net sizes gets reduced the most.
Comments