Editorial for COCI '16 Contest 5 #5 Poklon
Submitting an official solution before solving the problem yourself is a bannable offence.
We will solve the task using the offline method, where we first input all queries, and then process them. To begin with, let's define two functions, , that correspond to the position of the first left and the first right element, respectively, of the same value as the one at position . These two functions are easily computed, traversing from left to right, or from right to left, keeping track of the 'latest' of each value using a hash map, structure map
in C++ or a normal matrix, if we first compress the values. Let's observe a query and functions , . It is easily noticed that we will count in a position for query if . Using natural language: we want the first left appearance of the value to be before the left end of the interval, and the first right appearance before or at the right end of the interval, in addition that there is no other occurrence of the value in the interval. With this, we ensure the counting of each pair of two identical values exactly once. Now the task is reduced to the following problem: for an , increment by the solution of each query where and where .
In order to execute this query, we need to construct a tournament data structure over all intervals in the following way: for each node of the tournament that covers interval , we need to 'insert' the query if , in other words, . After this, for each , we need to insert the interval into all nodes of the tree of which the interval is made of (typical query or update operation in a tournament data structure). There are such nodes for each . After inserting queries and intervals into the tournament, we need to calculate the 'contribution' of each node to the queries located in that node. We perform this using the sweep technique and leave the implementation details as an exercise for the reader.
The total complexity of the given solution is . A solution of the complexity also exists, and is also left as an exercise for the reader.
Comments