#P9959. [USACO19JAN] Sleepy Cow Sorting B

[USACO19JAN] Sleepy Cow Sorting B

Problem Description

Farmer John is trying to line up his NN cows (1N1001\le N\le 100), conveniently numbered 1N1\ldots N, before they head to the pasture to eat breakfast.

Currently, the cows are standing in a line in the order p1,p2,p3,,pNp_1,p_2,p_3,\ldots,p_N, and Farmer John is standing in front of cow p1p_1. He wants to rearrange the cows so that their order becomes 1,2,3,,N1,2,3,\ldots,N, with cow 11 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 kk steps, where kk can be any integer in the range 1N11\ldots N-1. The kk cows she passes will move forward to make space, allowing her to be inserted into the position after those kk cows.

For example, suppose N=4N=4, and the cows initially are in the following order:

FJ: 4,3,2,14, 3, 2, 1

The only cow paying attention to FJ is cow 44. After he commands her to move back by 22 steps, the order becomes:

FJ: 3,2,4,13, 2, 4, 1

Now the only cow paying attention to FJ is cow 33, so on the second move he can command cow 33, 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 NN.

The second line contains NN space-separated integers p1,p2,p3,,pNp_1,p_2,p_3,\ldots,p_N, representing the cows' initial order.

Output Format

Output one integer: the minimum number of moves needed for Farmer John to sort these NN cows using an optimal strategy.

4
1 2 4 3
3

Hint

Translated by ChatGPT 5