Walking Along a Fence

시간 제한2초메모리 제한1024 MB

요약
직교 다각형으로 이루어진 울타리 위의 두 점이 주어질 때, 두 방향 호 중 더 짧은 거리를 각 쿼리마다 구한다.
난이도

보통10점 중 6점

유형
기하, 누적 합, 이분 탐색, 구현
정답자
아직 제출이 없습니다

문제

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), the location of each being 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 is connected to the two adjacent posts by fences that are either vertical or horizontal line segments, so the entire fence can be considered a polygon whose sides are parallel to the x or y axes (the last post connects back to the first post, ensuring the fence forms a closed loop that encloses the pasture). The fence polygon is "well-behaved" in that fence segments only potentially overlap at their endpoints, each post aligns with exactly two fence segment endpoints, and every two fence segments that meet at an endpoint are perpendicular.

Each cow has a preferred starting and ending position for her daily walk, each being points somewhere along the fence (possibly at posts, possibly not). Each cow walks along the fence for her daily walks, starting from her starting position and ending at her ending position. There are two routes that the cow could take, given that the fence forms a closed loop. Since cows are somewhat lazy creatures, each cow will walk in the direction around the fence that is shorter (if there is a tie, the cow may choose either direction).

Determine the distance that each cow walks.

입력

The first line of input contains NN and PP. Each of the next PP lines contains two integers representing the positions of the fence posts in clockwise or counterclockwise order. Each of the next NN lines contains four integers x_1x\_1 y_1y\_1 x_2x\_2 y_2y\_2 representing the starting position (x_1,y_1)(x\_1, y\_1) and ending position (x_2,y_2)(x\_2, y\_2) of a cow.

출력

Write NN integers as output, giving the distance that each cow walks.

예제1

  1. 예제 1

    입력
    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
    
    예상 출력
    2
    3
    3
    4
    4