Walking Along a Fence
InterviewTime limit2sMemory limit1024 MB
Given a rectilinear fence loop and each cow's start and end points on it, find the shorter walking distance along the fence for each cow.
- Level
Medium4 of 10
- Topics
- Prefix sum, Array, Implementation
- Solved
- No attempts yet
Problem
Farmer John's cows () each like to take a daily walk around the fence enclosing his pasture.
The fence consists of posts (, even). Each post is a different 2D point on a map of FJ's farm (). Each post connects to the two adjacent posts by fence segments that are either vertical or horizontal, so the fence is a polygon whose sides are parallel to the x or y axes. The last post connects back to the first post, so the fence forms a closed loop that encloses the pasture. Fence segments overlap only at their endpoints, each post matches exactly two segment endpoints, and every two segments that meet at an endpoint are perpendicular.
Each cow has a preferred starting position and ending position for her walk. Each position is a point somewhere on the fence, possibly at a post and possibly not. The cow walks along the fence from her starting position to her ending position. Because the fence is a closed loop, there are two possible routes. Cows are lazy, so each cow takes the shorter route (if the two routes tie, the cow may choose either one). Determine the distance each cow walks.
Input
The first line contains and . Each of the next lines contains two integers, the coordinates of a fence post, listed in clockwise or counterclockwise order. Each of the next lines contains four integers , the starting position and the ending position of a cow.
Output
Write integers, one per line, giving the distance each cow walks.