Torus Sea
Time limit2sMemory limit512 MB
On a torus of size N by M, a random walk moves diagonally each day; find the expected number of days to first reach (x, y), or -1 if unreachable.
- Level
Medium6 of 10
- Topics
- Probability, Graph, Math
- Solved
- No attempts yet
Problem
Sanggeun is sailing the Doughnut Sea. The sea has the shape of a torus and is divided into cells.

(Image by YassineMrabet from Wikimedia Commons, licensed under CC BY-SA 3.0.)
Every cell has coordinates with and . Coordinates are always kept as remainders modulo and , so the sea wraps around in both directions. Increasing the first coordinate from gives , and decreasing it from gives . The second coordinate wraps the same way modulo .
Sanggeun starts at and wants to reach . He moves once per day. From he goes to or to , each with probability . Here is the remainder in .
Write a program that computes the expected number of days until Sanggeun first reaches .
Input
The first line contains , , , , separated by spaces. (, , )
is not .
Output
Print the expected number of days until Sanggeun first reaches . This expected value is always an integer, so print a single integer with no decimal point and no trailing digits.
If cannot be reached, print -1.