Editorial for COCI '09 Contest 2 #4 Vuk


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.

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 0. Afterwards, we expand in a BFS manner increasing the distance by 1 for each patch. This can be done in \mathcal O(NM). 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 \mathcal O(NM \log(NM)).


Comments

There are no comments at the moment.