Editorial for Yet Another Contest 8 P1 - Permutation Sorting
Submitting an official solution before solving the problem yourself is a bannable offence.
Author:
Subtask 1
If the permutation is already sorted, then no operations are necessary, and the answer is .
Otherwise, we must sort exactly one subarray. Observe that the elements which are not part of this subarray form some prefix and suffix of the original permutation. Thus, it suffices to count the largest prefix and suffix which contain the correct elements, and count the number of remaining elements.
Time complexity:
Observation
Each index does not need to be involved more than one operation. Otherwise, we could take two operations which include this index, and merge their intervals to form a single operation with a smaller cost. Thus, it suffices to determine whether each index should be included in an operation or not. For any two adjacent indices which are both included in an operation, we would include them in the same operation.
Subtask 2, Alternative 1
For any index with , all of the cells between and (inclusive) must be included in at operation, in order for this element to end up at the correct position. If we mark these cells for all values of , then the number of cells marked at least once is the answer.
Time complexity:
Subtask 2, Alternative 2
An index does not need to be included in an operation if the following criteria holds:
- for all
It suffices to check this criteria naively for all .
Time complexity:
Subtask 3, Alternative 1
We can optimize alternative 1 of subtask 2. Construct a list of all intervals for all indices with . The answer is the size of the union of these intervals. We can use a standard interval merging algorithm, or use a difference array.
Time complexity: or
Subtask 3, Alternative 2
We can optimize alternative 2 of subtask 2. Simplify the second condition as , or equivalently since , . We can then keep a running prefix maximum as we loop through all indices .
Time complexity:
Comments