#P8623. Zigzag Building Distance

    ID: 21789 Type: Default 1000ms 256MiB

Zigzag Building Distance

Zigzag Building Distance

On planet X, the residential buildings in a community are arranged in a matrix with a fixed width. The buildings are numbered consecutively as 1,2,3,1,2,3,\ldots. When one row is full, numbering proceeds to the next row but in the opposite direction. For example, if the community has a width of 66, the numbering is as follows:

$$\begin{array}{cccccc} 1 & 2 & 3 & 4 & 5 & 6 \\ 12 & 11 & 10 & 9 & 8 & 7 \\ 13 & 14 & 15 & \cdots & & \end{array} $$

Given the width ww of the community and two building numbers mm and nn, your task is to calculate the shortest moving distance between them. Movement is allowed only in the four cardinal directions (up, down, left, right), which implies the distance between two buildings is their Manhattan distance in the grid.

To determine each building's position, note that if a building has number xx, then its row index is (r = \left\lfloor \frac{x-1}{w} \right\rfloor). For an even-indexed row (starting at 0), the column index is (c = (x-1) \bmod w). For an odd-indexed row, the ordering is reversed so that the column index is (c = w - 1 - ((x-1) \bmod w)). The Manhattan distance is defined as:

distance=r1r2+c1c2\text{distance} = |r_1 - r_2| + |c_1 - c_2|

where ((r_1, c_1)) and ((r_2, c_2)) are the positions of buildings mm and nn, respectively.

inputFormat

The input consists of a single line containing three integers separated by spaces: the width of the community ww, and the two building numbers mm and nn.

outputFormat

Output a single integer representing the minimum Manhattan distance between the two buildings.

sample

6 1 12
1