#P9959. [USACO19JAN] Sleepy Cow Sorting B
[USACO19JAN] Sleepy Cow Sorting B
Problem Description
Farmer John is trying to line up his cows (), conveniently numbered , before they head to the pasture to eat breakfast.
Currently, the cows are standing in a line in the order , and Farmer John is standing in front of cow . He wants to rearrange the cows so that their order becomes , with cow next to Farmer John.
Today the cows are a bit sleepy, so at any moment only the cow directly facing Farmer John will pay attention to his commands. In one move, he can command this cow to move back along the line by steps, where can be any integer in the range . The cows she passes will move forward to make space, allowing her to be inserted into the position after those cows.
For example, suppose , and the cows initially are in the following order:
FJ:
The only cow paying attention to FJ is cow . After he commands her to move back by steps, the order becomes:
FJ:
Now the only cow paying attention to FJ is cow , so on the second move he can command cow , and so on until the cows are sorted.
Farmer John is eager to finish sorting so he can go back to his farmhouse and eat his own breakfast. Please help him find the minimum number of moves required to sort the cows.
Input Format
The first line contains .
The second line contains space-separated integers , representing the cows' initial order.
Output Format
Output one integer: the minimum number of moves needed for Farmer John to sort these cows using an optimal strategy.
4
1 2 4 3
3
Hint
Translated by ChatGPT 5