#P9959. Sleepy Cow Sorting
Sleepy Cow Sorting
Sleepy Cow Sorting
Farmer John has N cows numbered from 1 to N (1 ≤ N ≤ 100) that are initially lined up in an arbitrary order p1, p2, ..., pN. He stands in front of cow p1 and wishes to rearrange the cows into increasing order (1, 2, 3, ..., N) so that cow 1 stands right beside him.
However, the cows are a bit sleepy today so only the cow at the front of the line listens to Farmer John's commands. In one operation, he may instruct this cow to move k positions back in the line (where 1 ≤ k ≤ N−1). As she moves, the k cows she passes all move one position forward to fill the gap.
For example, consider N = 4 with the initial order:
FJ: 4, 3, 2, 1
If FJ instructs cow 4 (at the front) to move 2 steps back, the order becomes:
FJ: 3, 2, 4, 1
Now, only the cow at the front (cow 3) listens, and Farmer John can continue issuing commands until the cows are in the order 1, 2, 3, 4. Your task is to determine the minimum number of commands required to achieve this sorted order.
Hint: Notice that if some suffix of the line is already in increasing order, those cows will never need to be moved. In fact, the answer is the index of the first cow that breaks this increasing pattern (when traversing from the back).
The answer can be computed by finding the longest suffix (say from position i+1 to N) where the sequence is strictly increasing, and then the minimum number of moves is i (using 0-indexed positions).
All formulas are formatted in LaTeX. For instance, the condition for selecting a valid move is given by: \(1 \leq k \leq N-1\).
inputFormat
The first line contains a single integer \(N\) (\(1 \leq N \leq 100\)). The second line contains \(N\) space-separated integers representing the initial order of the cows.
outputFormat
Output a single integer, representing the minimum number of commands that Farmer John must issue to arrange the cows in increasing order.
sample
4
4 3 2 1
3
</p>