Frog
Time limit1sMemory limit512 MB
Find the minimum total squared jump cost for a frog to travel from the lower bank to the upper bank across axis-aligned logs.
- Level
Medium7 of 10
- Topics
- Shortest path, Geometry, Graph, Heap
- Solved
- No attempts yet
Problem
In a hot, dry summer a hungry frog travels toward the land of flies, where water and food are plentiful. On the way it has to cross a river. The frog normally swims, but right now it is so hungry and tired that it can only walk and jump. Logs float on the river, and the frog can walk along a log or jump from one log to another.
Walking costs almost no energy, so the distance walked does not count. A jump of distance costs energy. The frog can jump a distance of at most at a time.
The river and both banks lie on an grid. is the segment whose endpoints are and . Each bank is a polyline through its vertices in the given order, and each log is a single segment. Every segment is parallel to the axis or to the axis. No two logs share a common part, and no log shares a common part with a bank.
The frog moves to any position on the same segment without spending energy. A bank is one connected polyline, so the frog also moves freely along a whole bank. The frog starts on the lower bank, and the trip ends the moment it reaches the upper bank.
Figure 1 shows an example on an grid. The lower bank consists of 7 segments, the upper bank consists of 11 segments, and the logs are , , , in that order.

Figure 1. Four logs on the river.
With , stepping on log 1 and then on log 3 costs energy, and no route costs less. With the frog cannot cross the river.
Write a program that computes the minimum energy the frog needs to cross the river.
Input
The first line has two integers and , the size of the grid ().
The second line has four integers , , , (, ). The lower bank has vertices, the upper bank has vertices, and logs float on the river. The frog jumps a distance of at most at a time.
Each of the next lines has two integers and (, ), one vertex of the lower bank. The vertices come in clockwise order, and the bottommost vertex, leftmost among those, comes first.
Each of the next lines has two integers and in the same format, one vertex of the upper bank. The vertices come in counterclockwise order, and the topmost vertex, leftmost among those, comes first.
On a bank, the segment joining two neighboring vertices is parallel to the axis or to the axis.
Each of the last lines has four integers , , , (, ) describing one log, the segment . Either or holds.
The lower bank and the upper bank do not meet.
Output
Print on one line the minimum energy the frog needs to cross the river. If the frog cannot cross the river, print -1.