#K6296. Minimum Reverse Operations
Minimum Reverse Operations
Minimum Reverse Operations
You are given an array of n integers. Your task is to determine the minimum number of operations required to sort the array in non-decreasing order by reversing the order of a contiguous subarray. In each operation, you may select a subarray defined by the indices \(l\) and \(r\) (1-indexed) and reverse it.
If the array is already sorted, no operations are needed. Otherwise, print the total number \(k\) of operations performed followed by the \(k\) pairs of indices where each pair \((l, r)\) represents a reversal operation.
The overall objective is to transform the array into its sorted (non-decreasing) order using the minimal number of reverse operations. For example, if the input array is [3, 1, 2]
, one valid sequence of operations is first reversing from index 1 to 3 to obtain [2, 1, 3]
, and then reversing from index 1 to 2 to finally get [1, 2, 3]
.
Note: All subarray indices are 1-indexed. The operations should be printed in the order they are applied.
inputFormat
The input is provided via standard input (stdin) and has the following format:
- The first line contains an integer
n
, the number of elements in the array. - The second line contains
n
space-separated integers representing the elements of the array.
outputFormat
Output the result to standard output (stdout) in the following format:
- The first line contains an integer representing the number of reverse operations performed.
- If the number of operations is greater than 0, each of the following lines contains two space-separated integers
l
andr
which denote the 1-indexed starting and ending positions of the subarray that was reversed. - If no operations are performed (i.e. the array is already sorted), simply output 0.
3
3 1 2
2
1 3
1 2
</p>