#K84042. Minimum Segment Reversals

    ID: 36331 Type: Default 1000ms 256MiB

Minimum Segment Reversals

Minimum Segment Reversals

You are given a bookshelf with N books arranged in an arbitrary order. The books are labeled with distinct integers. Your task is to find the minimum number of segment reversals needed to sort the bookshelf in ascending order. A segment reversal operation reverses the order of a contiguous block of books.

It can be proved that the minimum number of reversals required is given by \[ \text{result} = N - L, \] where \(L\) is the length of the longest common subsequence (LCS) between the original order and the sorted order of the books.

For example, if N = 5 and the bookshelf order is [4, 3, 2, 5, 1], the sorted order is [1, 2, 3, 4, 5]. The LCS length is 2 (for example, [3,5] or [2,5]), so the answer is 5 - 2 = 3 reversals.

inputFormat

The first line contains an integer N, the number of books. The second line contains N space-separated integers representing the current order of the books.

outputFormat

Output a single integer representing the minimum number of segment reversals needed to sort the bookshelf.

## sample
5
4 3 2 5 1
3

</p>