Editorial for Baltic OI '07 P4 - Building a Fence


Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.

We can build a graph G from the input data by considering all rectangle corners that do not lie strictly inside any other rectangle as a vertex. Since there are at most 100 rectangles, the graph G will have at most 400 vertices. We add an edge between two pairs of vertices x, y in G if the rectangular area between the corners they represent is empty. The weight (length) of this edge will be the Manhattan distance between x and y. A closed path in G will correspond to a fence where the length of the path is the length of the fence. It is easy to see that an optimal fence can always be built according to the edges in G (non-horizontal/vertical edges can be split into one horizontal and one vertical component).

We must now make sure that the path goes around the main mansion. To understand the idea outlined below, remember that to determine if a point lies inside a polygon (which the fence can be conceived as), one can draw a straight line from the point to some known place outside the polygon and count the parity of the number of line intersections.

Let X, Y be the coordinates of the top left corner of the mansion. The idea is to extend the graph G into two layers, corresponding to an even or an odd number of revolutions. Call this new graph H. When traversing an edge that corresponds to the movement (x_1, y_1) \to (x_2, y_2) where x_1 \le X, x_2 > X and y_1, y_2 \le Y, the number of revolutions traversed increases by 1. If we go the other direction, it decreases. In both cases the parity of the number of revolutions changes. Now the problem becomes to find the shortest path between some node and the same node but in the other layer of the graph H. This can be solved using a standard Dijkstra's algorithm (simplified version is enough), once for each node in the first layer in H.


Comments

There are no comments at the moment.