ACM ICPC World Finals 2012
The first step is to figure out where to put the water pressure level. Or rather, to blindly try all possibilities for the water pressure, which incurs a factor of N on the running time.
Given the water level, consider the induced subgraph on the set of points that are below water. This consists of a set of connected components C1 , . . . , Cr , which we can think of as forming a (complete, weighted) graph G, in which the distance from component C1 to component C2 is the minimum distance between a point in C1 and a point in C2 which both have an available pipe hole. We want to find a path from the component containing s (say, C1 ), to the component containing t (say, Cr ), possibly using some intermediate components at shortcuts. The total cost of the path is the sum of distances of edges used, plus the cost of plugging the holes in the used components. The cost of plugging the holes in some intermediate component Ci is 0.5 · (#{open holes in Ci } − 2), because all holes except the two that we use to connect Ci to the previous and next component need to be plugged. Similar calculations apply for the components C1 and Cr . Note that intermediate components must have at least two holes (and the source and destination components must have at least one hole). A special case has to be dealt with: when s and t are in the same component, no path is needed and the plugging cost is just 0.5 · #{holes in C1 }.