Prime Village
InterviewTime limit2sMemory limit256 MB
Given 2D points, find the shortest path from a start to a target where every edge must have a prime truncated Euclidean distance.
- Level
Medium6 of 10
- Topics
- Graph, Shortest path, Number theory, Brute force
- Solved
- No attempts yet
Problem
The residents of Prime Village follow a very unusual rule: they go to a place only if the distance to it is a prime number.
Seungwook, a resident of Prime Village, has an errand in village A, which is far from Prime Village, so he has to travel there. He would like to go from Prime Village to village A in one move, but he cannot if the distance between the two villages is not prime. In that case he has to pass through other villages on the way. He can move to an intermediate village only if the distance from his current position to that village is also prime.
The positions of Prime Village, the villages he can pass through, and village A are given as points on the coordinate plane. Help Seungwook find the shortest route to village A that follows the rule of Prime Village.
The distance between two villages is taken as the integer part of the distance between the two points. For example, a distance of is truncated and treated as . The truncated value is used both to test for primality and when adding up the distances traveled.
Input
The first line contains the position of Prime Village and the position of village A, in the order .
The second line contains (), the number of villages he can pass through.
Each of the next lines contains the position of one village he can pass through.
Every coordinate is an integer whose absolute value does not exceed .
Output
Print the total distance of the shortest route to village A that follows the rule of Prime Village. The total is the integer sum of the truncated distances of the individual moves.
If there is no way to reach village A while following the rule, print .
Hint

In the first example, the distance between Prime Village and village A is , which is treated as , and is not prime. Passing through village C makes both moves , that is , so the total distance is .