Milan cemetery

Legend has it that SWERC teams have a curse with cemeteries. This year,
Xavier and Izan woke up the day before the competition in Milan’s
cemetery. It was so monumental that they decided to visit everything.
However, they didn’t want to get too tired.

0.65 The cemetery is an n × m grid, and they woke up in position (x, y).
Can you help them figure out the minimum number of changes of direction
needed to visit every cell? They can only move in the N, S, E, O
directions.

For instance, to the right you can see the first case of the sample. It
is possible to visit all the cells with only four changes of direction.

0.33

(4,3)

(0,0)(4,0)(4,3)(0,3)

(1,0)(1,3) (2,0)(2,3) (3,0)(3,3) (0,1)(4,1) (0,2)(4,2)

(2.5,1.5)0.07 (2.5,1.5)(0.55,1.5) (0.5,1.5)(0.5,2.45)
(0.5,2.5)(3.45,2.5) (3.5,2.5)(3.5,0.55) (3.5,0.5)(0.5,0.5)

Input

Input consists of several cases, each one with n, m, x and y. Assume
that both n and m are between 1 and 10⁶, 1 ≤ x ≤ n, and 1 ≤ y ≤ m.

Output

For each case, print the minimum number of changes of direction required
to visit the whole cemetery.

Problem information

Author: Edgar Moreno

Generation: 2026-01-25T12:05:17.102Z

© Jutge.org, 2006–2026.
https://jutge.org
