Editorial for COCI '09 Contest 2 #4 Vuk
Submitting an official solution before solving the problem yourself is a bannable offence.
First, let us find for each patch what is the smallest distance to some tree. We do this by running a BFS algorithm, we start at all patches containing a tree, marking them with distance . Afterwards, we expand in a BFS manner increasing the distance by for each patch. This can be done in . Now let us search for the best path from Vjekoslav's starting position. We maintain a sorted data structure (a heap, for example) that stores all patches not yet visited that are next to some patch we already visited. We sort the patches by decreasing tree distance. At first, the heap contains exactly one patch, Vjekoslav's starting patch. As we visit each patch, we add all his neighbors to the heap and mark it as solved. The solution for that patch is his own distance, or the solution for the patch we visited it from, whichever is smaller. We can terminate the search when we visit the cottage patch. The worst case is .
Comments