DVD
Time limit1sMemory limit512 MB
A DVD logo rectangle bounces off the TV walls; find the earliest time its corner reaches a TV corner, or report that it never does.
- Level
Medium7 of 10
- Topics
- Math, Number theory, Simulation, Binary search
- Solved
- No attempts yet
Problem

The DVD logo can be represented as a rectangle (even though it does not look like one) whose sides are parallel to the horizontal and vertical sides of the TV. The logo moves with a horizontal velocity of +1 or -1 and a vertical velocity of +1 or -1. When the logo hits a horizontal side of the TV, its vertical velocity is reversed, and when it hits a vertical side, its horizontal velocity is reversed.
Wookje believes that anyone who witnesses the moment the DVD logo hits a corner of the TV will have good luck that day. Seeing that moment on an ordinary TV is very rare. One day, Wookje had a clever idea. Why not figure out exactly when the logo will hit a corner and then run over to watch at precisely that moment?
Tell Wookje the minimum number of seconds he must wait for the DVD logo to hit a corner of the TV.
Input
The first line gives the width w and height h of the DVD logo, and the width W and height H of the TV. (1 ≤ w, h, W, H ≤ 106, w+2 ≤ W, h+2 ≤ H)
The second line gives the initial x-coordinate and y-coordinate of the top-left corner of the DVD logo. (0 < x < W-w, 0 < y < H-h) The coordinate of the top-left corner of the TV is (0, 0). The x-coordinate increases to the right, and the y-coordinate increases downward. The bounds use < instead of ≤ to mean that the DVD logo does not start out touching a wall.
The third line gives the horizontal velocity (1 or -1) and the vertical velocity (1 or -1) of the DVD logo.
Every number in the input is an integer.
Output
Print the minimum time to wait until the DVD logo hits a corner of the TV. If the logo cannot hit a corner, print -1.