PROBLEM LINK:
Contest Division 1
Contest Division 2
Contest Division 3
Contest Division 4
Setter: Utkarsh Gupta
Tester: Nishank Suresh, Utkarsh Gupta
Editorialist: Pratiyush Mishra
DIFFICULTY:
2349
PREREQUISITES:
None
PROBLEM:
Let A be a permutation of \{1,2,3, \dots, N\}.
We define a function f(A) as the minimum number of increasing subarrays into which the permutation A can be partitioned.
For example f(\{5, 1, 4, 2, 3\}) = 3, as the minimum number of increasing subarrays it can be partitioned into is 3. The partitions are: \{5\}, \{1, 4\}, and \{2, 3\}.
Chef has a permutation P of \{1,2,3, \dots, N\}.
Chef wants to sort the permutation P. For that, he can choose any two indices (i, j) (1 \leq i \lt j \leq N) and swap the elements P_i and P_j such that the value of f(P) does not increase after the swap.
Help Chef sort the permutation in at most N^2 swaps.
EXPLANATION:
In order to sort the permutation P we will first take the first two increasing sequences of the array. In case the array has only one increasing sequence then that implies that the array is already sorted. Now after selecting the first two increasing sequences, we will sort them to make it a single increasing sequence. Again we will repeat the operation of selecting first two increasing sequences and sorting it till the whole array is sorted.
Now let’s talk about how we will sort the first two increasing sequences, say L and R. We will select the largest element from R, say r that is smaller than the largest element of L, then using binary search we find the smallest element in L that is larger than r and swap the two. By repeatedly following this operation we can sort L and R into a single increasing sequence without increasing f(P) and in atmost N^2 swaps.
TIME COMPLEXITY:
O(N^2log(N))
SOLUTION:
Editorialist’s Solution
Setter’s Solution
Tester1’s Solution
Tester2’s Solution