Editorial for WC '18 Contest 1 S3 - Reach for the Top
Submitting an official solution before solving the problem yourself is a bannable offence.
This problem may be solved with two distinct approaches.
Graph Theory Approach
Let's represent the rope as a directed graph with nodes (numbered from to ), with each node representing Bob holding onto the rope at a height of . Each action which would take Bob from a height to another height then corresponds to an edge from node to node . We're then looking for the shortest distance (minimum sum of edge weights) from node to any node from upwards.
BFS (Breadth First Search) is a well-known algorithm which can be used to compute shortest distances on unweighted graphs such as this one. The time complexity of BFS is , where is the number of nodes in the graph, and is the number of edges. In this case is in , but is in , as each node has outgoing edges corresponding to possible drop actions from it. This gives us an overall time complexity of , which is too slow to earn full marks.
It's possible to optimize this approach by making the graph weighted, and adding an extra set of nodes to it. Let's refer to the original nodes as , and the new nodes as , with each new node representing Bob being mid-drop at a height of . We'll want to have a weight- edge from each node to , representing the continuation of a drop. The start of a drop can then be represented by a weight- edge from each node to , while the end of a drop can be represented by a weight- edge from each node back to . This removes the need for outgoing drop-related edges from each node!
We can no longer use BFS due to the graph being weighted, but in this case, we can use a variant of it which works when all edge weights are equal to either or . This variant uses a deque rather than a queue, and pushes nodes coming from weight- edges onto the front rather than the back of the deque. It similarly runs in . Since and are now in , this gives us an overall time complexity of , which is fast enough. Note that Dijkstra's algorithm could be used instead, though it's slower and slightly more complex.
Dynamic Programming Approach
Let be the minimum number of jumps required for Bob to hold onto the rope at a height of , and let be the maximum height such that . Initially, we have and , and we'll let for convenience. We'll proceed to fill in the DP values in a series of phases corresponding to increasing values, starting with . For each , we'll iterate over heights from up to . For each such , either , or has yet to be filled in and we can set it to (due to dropping down from a height of ). Either way, we'll end up with this phase of DP values all filled in, and from each we can fill in as well, while updating as appropriate. As soon as we arrive at , must be the answer, and if we instead run out of new phases to explore, then the answer must be -1
.
Comments