Square Running
Time limit1sMemory limit1024 MB
Given n runners on concentric lanes around a rectangle, find the earliest second when every runner is in the photographer's row or column, or report -1.
- Level
Hard8 of 10
- Topics
- Number theory, Math, Implementation
- Solved
- No attempts yet
Problem
Runsberg citizens are keen on sports, especially running. Standard marathons bored them, so they decided to organize a marathon in Minecraft style. The event will be held on Runsberg's Central Square. Citizens believe that the most important thing in sports is not winning but participating, so the goal of the square running is not to win but to take a beautiful photo of all participants.
The Central Square is a rectangle divided into unit squares. Rows are numbered from top to bottom starting from one, and columns are numbered from left to right starting from one. Each unit square has coordinates and , its row and column number.
A rectangular grass field lies on the square, with sides parallel to the square's sides. Its top left unit square is , and its bottom right unit square is . There are lanes for runners around the grass field. Lane is at distance from the field's border, and runner is on lane . Runner starts from the unit square . All runners start at the same time at the same speed. Every second, each runner moves from the current square to the next square in their lane, counterclockwise.
A photographer stands on the unit square of the grass field. The photographer uses a dual-lens camera that takes a photo in two opposite directions at once. A photo is beautiful if, at the moment of the shot, all runners are in row or in column . Because of the camera, runners may be in the same row on both the left and right of the photographer, or in the same column above and below.
Find the minimum number of seconds after the start after which the photographer can take a beautiful photo. If no beautiful photo is possible under these conditions, find that out instead.
Input
The first line contains an integer (), the number of runners. The second line contains six integers , , , (, ), (), and (). These are the top left corner, the bottom right corner, and the photographer's position. It is guaranteed that is divisible by 4.
The next lines each contain two integers and , the starting coordinates of runner . Each start lies on lane , each lane holds exactly one runner, and lane is at distance from the field's border.
Output
Print the minimum number of seconds after the start at which the photographer can take a beautiful photo, or if that is impossible.
Hint

Starting positions of the runners.

Positions of the runners after 3 seconds. All runners are in row , so the photographer can take a beautiful photo.