Lasers and Mirrors
Time limit2sMemory limit512 MB
Given a laser, a barn, and up to 100,000 posts, find the fewest posts to mount mirrors on so the beam travels from laser to barn.
Problem
The cows are putting on another laser light show.
The laser they got for this show is so large that they cannot move it from the spot where it was delivered. They want to send its beam to the barn on the other side of the farm. On the map of the farm the laser and the barn are points in the plane. The cows aim the laser so that the beam leaves horizontally or vertically, parallel to the x axis or the y axis. They then bounce the beam off a few mirrors to bring it to the barn.
The farm has fence posts () standing at distinct points. No post stands where the laser or the barn is. The cows can mount a mirror on any posts they like. A post with no mirror lets the beam pass straight over it without changing direction. A post with a mirror holds it diagonally, as / or \, so it turns a horizontal beam into a vertical one and a vertical beam into a horizontal one. The cows choose the orientation of each mirror.
Compute the smallest number of mirrors that brings the beam from the laser to the barn.
Input
The first line contains five space separated integers , , , , , where is the location of the laser and is the location of the barn.
Each of the next lines contains the coordinates and of one fence post. Every coordinate is an integer between and , inclusive. The posts are at distinct points, and none of them is at the laser or at the barn.
Output
Print the smallest number of mirrors needed to send the beam to the barn. If no arrangement of mirrors sends the beam to the barn, print -1.