Editorial for Baltic OI '07 P4 - Building a Fence
Submitting an official solution before solving the problem yourself is a bannable offence.
We can build a graph 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 rectangles, the graph will have at most vertices. We add an edge between two pairs of vertices in if the rectangular area between the corners they represent is empty. The weight (length) of this edge will be the Manhattan distance between and . A closed path in 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 (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 be the coordinates of the top left corner of the mansion. The idea is to extend the graph into two layers, corresponding to an even or an odd number of revolutions. Call this new graph . When traversing an edge that corresponds to the movement where , and , the number of revolutions traversed increases by . 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 . This can be solved using a standard Dijkstra's algorithm (simplified version is enough), once for each node in the first layer in .
Comments