luogu#P5200. [USACO19JAN] Sleepy Cow Sorting G
[USACO19JAN] Sleepy Cow Sorting G
Background
USACO January 2019 contest, Gold Group, Problem 2.
Problem Description
Farmer John is trying to line up his cows (), numbered for convenience, before they head to the pasture for 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 time, only the cow directly facing Farmer John will pay attention to his commands. In one operation, he can command this cow to move back along the line by steps, where can be any number from to . The cows she passes will move forward to make space, allowing her to be inserted right behind those cows in the line.
For example, suppose , and the cows start in the following order:
FJ: 4 3 2 1
The only cow paying attention to FJ is cow . After he commands her to move back steps, the line becomes:
FJ: 3 2 4 1
Now the only cow paying attention to FJ is cow , so in the second operation he can give a command to 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 enjoy his own breakfast. Please help him find a sequence of operations that sorts the cows using the minimum number of operations.
Input Format
The first line contains .
The second line contains space-separated integers: , describing the cows' initial order.
Output Format
The first line contains an integer , the minimum number of operations needed to sort the cows.
The second line contains space-separated integers , each in the range . If in the -th operation, FJ commands the cow facing him to move back steps, then after operations the cows should be sorted.
If there are multiple optimal sequences of operations, your program may output any one of them (though in practice, the solution is unique).
4
1 2 4 3
3
2 2 3
Hint
Translated by ChatGPT 5