Editorial for IOI '05 P2 - Mountain
Submitting an official solution before solving the problem yourself is a bannable offence.
At the beginning, let us denote by the number of input lines starting with letter I
(i.e. reconfigurations). Similarly, let be the number of rides.
Simple solutions
One possible simple, although not optimal, solution is to represent the trail as a vector , where denotes the elevation after the rail. The complexity of processing a reconfiguration (we call this operation insertion) is . Single query about a ride also takes , so the total time complexity is . Moreover, memory complexity is which is far too high to not exceed the memory limit in large test cases.
Another simple approach is to represent the track as a sorted list of disjoint intervals such that throughout each interval, the difference of elevation over every rail is the same. This way we have insertion and query complexity of , so the entire solution is . Memory complexity is .
Model solution
A data structure used in the model solution is a binary tree. Each of its nodes describes an interval (i.e. a number of consecutive rails) , for some integers and . The information contained in the node is
The node is a leaf if all the values are equal. In this case computing and is trivial. Otherwise, the node has two sons, with assigned intervals and . In this case and are computed as and . The root of the tree represents the interval .
The key operation is reconfiguration of the track. It requires inserting or modifying at most nodes into the tree. Similarly, processing a query about a ride requires traversing at most nodes. Therefore, such a solution has time complexity of and memory complexity .
Even better solution
We are not required to process the input line by line. Instead, we can read in the entire input and know in advance, which parts of the track will be reconfigured at all. Let be a sorted vector of the ends of all the intervals contained in all the I
-records of the input. We can also assume, that the length of is some power of (if not, we extend by adding some large values).
Now we use a tree very similar to the one described in the previous section. The difference is, that each node describes an interval . We can store such a tree in a single vector, just like in the standard implementation of a heap. Since the size of is , so the total time complexity is and memory complexity is reduced to .
Comments