Under construction

Still being built. Things may change

Walking Along a Fence

Interview

Time limit2sMemory limit1024 MB

Summary
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 NN cows (1≤N≤1051 \leq N \leq 10^5) each like to take a daily walk around the fence enclosing his pasture.

The fence consists of PP posts (4≤P≤2⋅1054 \leq P \leq 2\cdot 10^5, PP even). Each post is a different 2D point (x,y)(x,y) on a map of FJ's farm (0≤x,y≤10000 \leq x, y \leq 1000). 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 NN and PP. Each of the next PP lines contains two integers, the coordinates of a fence post, listed in clockwise or counterclockwise order. Each of the next NN lines contains four integers x1x_1 y1y_1 x2x_2 y2y_2, the starting position (x1,y1)(x_1, y_1) and the ending position (x2,y2)(x_2, y_2) of a cow.

Output

Write NN integers, one per line, giving the distance each cow walks.

Examples1

  1. Example 1

    Input
    5 4
    0 0
    2 0
    2 2
    0 2
    0 0 0 2
    0 2 1 0
    2 1 0 2
    1 0 1 2
    1 2 1 0
    
    Expected output
    2
    3
    3
    4
    4