SRM 729, D1, 450-Pointer (FrogSquare)

James S. Plank

Tue Oct 2 14:23:43 EDT 2018
Revised: Mon Oct 11 15:44:58 EDT 2021

In case topcoder's servers are down

Here's a summary of the problem:

Examples

#    n     d     sx     sy     tx     ty    answer  Comments
------------------------------------------------------------------------------------
0   100    10    0      0      3      4       2     Jump to (99,99) and then to (4,2)
1   100     5    0      0      3      4       1     sqrt(4*4+3*3) = 5
2   100   200    0      0      3      4      -1     Can't jump anywhere from 0,0
3    10     7    4      4      5      5       3
4     1     1    0      0      0      0       0

Testing yourself

Standard -- see "Cryptography" if you need to see the workflow.

Hints

Shortest path through an unweighted graph may be implemented with BFS, and is O(E). The problem here is that E can be 1012. Here's the realization that allowed me to solve the problem:

If you don't go directly from start to finish, there is a shortest path that only involves nodes on the edges of the square.

Now you only have 4000 potential nodes, and your BFS can complete in time. If you're presenting this problem in CS494, I want you to prove the realization (and of course illustrate it very nicely graphically). That's how I solved it when I did the problem for topcoder. I constructed the graph on the fly, while I did the BFS.

I'll also state that if you're solving this in a programming competition like Topcoder, stop here and don't think about it any more. The thinking is more likely to get you into trouble, and this solution is fast enough.

However, if you're presenting this for CS494/594, read on:


But There's More

You can break it into cases and solve it in O(1) time: Thanks to CS594 students Adam Tutko, who first saw an O(1) solution, and to Everett Rush for helping me think more about the solution.