#P9204. Firebird's Diagonal Moves

    ID: 22359 Type: Default 1000ms 256MiB

Firebird's Diagonal Moves

Firebird's Diagonal Moves

Mihong can control a mystical firebird. The firebird is represented as a chess piece A placed on an infinitely large chessboard at position \( (x_1,y_1) \). The piece \( A \) moves according to the following rules:

  • On odd-numbered moves, \( A \) can only move one cell to the top-right or bottom-left. That is, from \( (x,y) \) it can go to \( (x+1,y+1) \) or \( (x-1,y-1) \).
  • On even-numbered moves, \( A \) can only move one cell to the bottom-right or top-left. That is, from \( (x,y) \) it can go to \( (x+1,y-1) \) or \( (x-1,y+1) \).

Note that the chessboard is infinite; hence the coordinates \( x \) and \( y \) may be negative. In every move, \( A \) must move (it cannot remain in place).

Your task is to compute the minimum number of moves required to move \( A \) from its starting position \( (x_1,y_1) \) to the target position \( B=(x_2,y_2) \). If it is impossible, output \( -1 \). Specially, if \( A \) is already at \( B \), the answer is \( 0 \).

For example, when \( A=(2,7) \) and \( B=(5,2) \), one optimal solution requires \( 9 \) moves. (The red segments in the figure indicate the moves on odd-numbered turns and the blue segments indicate the moves on even-numbered turns.)

It can be observed that if we define two auxiliary variables \( u=x+y \) and \( v=x-y \), then the odd moves change only \( u \) by \( \pm2 \) and the even moves change only \( v \) by \( \pm2 \). In particular, if we let

\[ \begin{aligned} u_{req} &= (x_2+y_2) - (x_1+y_1),\\ v_{req} &= (x_2-y_2) - (x_1-y_1), \end{aligned} \]

then a necessary condition for reachability is that the parities of \( x_1+y_1 \) and \( x_2+y_2 \) match, and \( v_{req} \) must be even. Furthermore, if we let \( r=\lceil k/2\rceil \) and \( s=\lfloor k/2\rfloor \) be the number of odd and even moves respectively in a sequence of \( k \) moves, then the sums obtainable by the odd moves are of the form

\[ 2\times(2t-r)=4t-2r,\quad t=0,1,\ldots,r, \]

and similarly for the even moves. Your program should find the minimum \( k \) such that \( u_{req} \) is reachable with \( r \) moves and \( v_{req} \) is reachable with \( s \) moves.

inputFormat

The input consists of a single line containing four space-separated integers \( x_1, y_1, x_2, y_2 \), representing the starting and target coordinates.

outputFormat

Output a single integer representing the minimum number of moves needed to move from \( (x_1,y_1) \) to \( (x_2,y_2) \). If it is impossible, output \( -1 \).

sample

0 0 0 0
0