#P10275. Shortest Walk on the Fence

    ID: 12275 Type: Default 1000ms 256MiB

Shortest Walk on the Fence

Shortest Walk on the Fence

Farmer John's NN cows (1N1051 \le N \le 10^5) love to take a walk along the fence surrounding his pasture. The fence is a closed polygon with PP posts (4P21054 \le P \le 2\cdot10^5, PP even), where each post is given by a unique coordinate (x,y)(x,y) with 0x,y10000 \le x,y \le 1000. Consecutive posts are connected by segments that are either horizontal or vertical, and the polygon is simple, meaning that the segments only intersect at their endpoints (with each intersection being perpendicular). Each cow has a preferred starting and ending point on the fence (which may lie exactly at a post or somewhere along a segment). Since the fence forms a closed loop, there are two possible routes between the two points. A cow will always choose the shorter route (if both are equal, either may be chosen). Your task is to determine the distance each cow walks along the fence.

inputFormat

The input begins with a line containing two integers NN and PP.

The next PP lines each contain two integers xx and yy, which give the coordinates of the fence posts in the order they appear along the fence (the PPth post is connected back to the first).

This is followed by NN lines, each containing four integers x1x_1, y1y_1, x2x_2, y2y_2. These represent the starting and ending points on the fence for a cow. It is guaranteed that these points lie on the fence.

outputFormat

For each cow, output a single line with the length of the shorter path along the fence from the starting point to the ending point.

sample

3 4
0 0
0 10
10 10
10 0
0 0 10 10
0 5 10 5
0 10 10 0
20

20 20

</p>