Editorial for COCI '14 Contest 5 #5 Jabuke
Submitting an official solution before solving the problem yourself is a bannable offence.
The simplest approach to solving this task, which was enough for  of points, is to check for all possible trees if they are candidates for the closest tree per each query. This algorithm has the complexity of 
.
In order to reduce complexity per query, we need to reduce the number of candidates for the closest tree. Let's solve a simpler problem. For a given location of the fall of an apple , determine the closest tree located at column 
.
If we denote rows with  and 
 so that 
 is the first line above row 
 such that column 
 contains an apple, and 
 is the first line below row 
 such that column 
 contains an apple, it is clear that 
 and 
 are the only possible candidates for the closest tree in that column.
Therefore, in order to answer the initial question, we need to check  trees per column. If we had a quick way of determining exactly which two trees these are per column, the answer to each query could be found in complexity 
.
To quickly find all possible candidates per column, we can maintain two matrices  and 
. Matrix 
 stores the first tree above position 
, and matrix 
 stores the first tree below position 
, given the fact that both fields contain 
 if there is a tree located at field 
.
To maintain the matrices described above, when inserting a new tree, we need to update values in the column where the tree grew, which results in  operations per query.
The final complexity of this algorithm is , which was sufficient for all points.
There is an alternative solution that uses BFS.
Comments