Editorial for DMOPC '21 Contest 3 P4 - Sorting Subsequences
Submitting an official solution before solving the problem yourself is a bannable offence.
Author:
Subtask 1
Let's imagine the array as a line of nodes. We add a directed edge from to if should be at the current position of in the optimal solution. For example, the graph representing the solution to the sample case is shown below, with different colours distinguishing different groups of indices selected in the sorting process:
By the definition of lexicographical minimum, we want to minimize the value of the first element, then the second, and so on. Therefore, the first thing we want to do is to draw an edge from to the element at the first index. Then, similarly for , we want to draw an edge from it to the element at the second index. If this isn't possible, we will try , then , then , etc. In general, for each index, we want the smallest element possible pointing to that index.
Note that as we move through this process, we will form chains of directed edges connecting the nodes together. We know that it is possible to draw an edge from to if it falls into one of these two categories:
- and are part of different chains, and the combined number of nodes in the chains does not exceed .
- and are part of the same chain, and connecting to completes a directed cycle.
It is possible to directly simulate this process with a nested for-loop, maintaining the necessary information with DSU.
Time Complexity:
Subtask 2
Instead of the inner for-loop from the previous solution, we can simulate it with a segment tree indexed by values that stores the size of the component for each value (for example, stores the size of the chain containing the element ). For each iteration of the outer loop, we are looking for the least index in the segment tree with a value no greater than where is the size of the component of . This can easily be found in time by walking down the segment tree if we store the minimum of all values in each node of the segment tree.
Time Complexity:
Comments