问题
I am having trouble finding the Optimal Dynamic Programming solution to a problem and would greatly appreciate any help. The optimal solution is O(T^2+M); I can only find a solution which is O(NM^2). The problem is:
There are N lockers that are labeled 1,2...N. Each locker is locked, but can be opened using it's unique key. Copies of the key to each locker are in its adjacent lockers; i.e. a copy of the key to locker i is placed in locker i+1 and i-1 (the key to locker 1 is only in locker 2 and the key to locker N is only in locker N-1)
T tennis balls are inside T distinct lockers (and you know which lockers they are in). You are given keys to M of the lockers and your goal is to collect all of the tennis balls by opening the least number of lockers.
My only hint given is: Hint: Can you efficiently decide whether there exist at least one tennis ball between the ith and jth locker?
回答1:
First place a dummy cell at N + 1 with a key and no tennis ball.
Now start at the second key, and proceed until the last key (which, you should note, is a dummy key).
At each iteration, calculate the optimal solution to the tennis balls to the left of the current key (inclusive) for two cases: a. the current key is used, and b. the current key is not used. The optimal solution should also record the rightmost key actually used.
If the current key is not used, then use the previous best two solutions to update the cost, using the rightmost key actually used for covering the balls to the left of the current key (inclusive). If the current key is used, then for each of the balls to the left of the current key (inclusive), calculate whether it pays to open from this key or the previously used key (it depends on the midpoint between the keys).
The overall solution is the one that is at the dummy N + 1 cell, and doesn't use the key in it.
来源:https://stackoverflow.com/questions/34869244/dynamic-programming-tennis-balls-lockers-and-keys