Baltic Olympiad in Informatics: 2010 Day 1, Problem 1
The Infinite city is divided into unitary square blocks by an infinite number of south-north and west-east two-way streets. One of the south-north streets is labeled , and the street numbers increase to the east and decrease to west. Similarly, one of the west-east streets is labeled , and the numbers increase to the north and decrease to the south.
Every intersection is labeled by an ordered pair of numbers of the streets that intersect (the first being the number of south-north street). Some street sections are more important and are called main streets.
One day sheriff Wolf (the fiercest caretaker of the Infinite city) is patrolling the streets and at intersection he notices a car with a few members of the well-known BEAR gang. Wolf has heard of the BEARs' plans to break into the city's Honey Warehouse, which is located near the intersection , and decides to stop them.
However, they haven't committed any crime so far and Wolf can't arrest them. But he has the authority to stop his car at any intersection and block exactly one of the four unit segments that meet at this intersection. However he can't block a unit segment that belongs to a main street.
So Wolf decides to pursue the BEARs and just before they reach an intersection, he may overtake their car and block one of the four unit segments at the intersection. The BEARs will be able to drive into the intersection, but they won't be able to exit the intersection to a segment blocked by the sheriff's car.
The sheriff wants to keep the BEARs as far away from the Honey Warehouse as possible. Find the maximum distance , such that any intersection the BEARs may reach satisfies the condition .
Constraints
Input Specification
The first line of input contains two integers and , the starting point of the BEARs. The second line contains one integer , the number of main streets. Each of the following lines contains four integers: , meaning that the street section between intersections and is a main street. Either or holds.
Output Specification
Output the maximum value of .
Sample Input
3 3
3
1 0 3 0
0 0 0 3
3 0 3 1
Sample Output
1
Explanation
The following figure illustrates how the BEARs can get to within distance of the warehouse:
Thicker black segments represent main streets. The sheriff cannot block unit segments belonging to main streets.
Even though the BEARs may continue trying forever, the sheriff can prevent them from ever getting closer to the warehouse.
Comments