Editorial for COCI '10 Contest 5 #6 Slika
Submitting an official solution before solving the problem yourself is a bannable offence.
First, observe that we can get rid of all SAVE
and LOAD
commands with time complexity. We process the sequence of commands in reverse order, starting from the last one down to the first one. Whenever a LOAD
command is to be processed, we ignore all commands between this command and the corresponding SAVE
command. With this approach, we obtain an equivalent sequence of commands which consists of only PAINT
commands.
This problem can now be solved using a sweep-line algorithm. Traversing the painting row by row, we keep two tournament trees; a red one and a white one, for convenience. The red tree will contain the checkerboard patterns in which even squares are painted in the current row, while the white tree will contain the patterns in which odd squares are painted in the current row. As we traverse rows, we swap those two trees before advancing to the next row. The tree nodes will contain the sets of patterns which cover the corresponding intervals, sorted by the time of painting.
Note that insertion and removal of a pattern has time complexity, while a query for any square has time complexity, which yields the total time complexity of .
Alternatively, the task can be solved with the union-find algorithm, in time complexity . This is left as an exercise for the reader.
Comments