## Editorial for Yet Another Contest 8 P1 - Permutation Sorting

Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.

Author: Josh

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.

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:

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:

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