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 NN cows (1N1051\le N\le 10^5), numbered 1N1\ldots N for convenience, before they head to the pasture for 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 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 kk steps, where kk can be any number from 11 to N1N-1. The kk cows she passes will move forward to make space, allowing her to be inserted right behind those kk cows in the line.

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

 FJ: 4 3 2 1

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

 FJ: 3 2 4 1 

Now the only cow paying attention to FJ is cow 33, so in the second operation he can give a command to 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 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 NN.
The second line contains NN space-separated integers: p1,p2,p3,,pNp_1,p_2,p_3,\ldots,p_N, describing the cows' initial order.

Output Format

The first line contains an integer KK, the minimum number of operations needed to sort the cows.

The second line contains KK space-separated integers c1,c2,,cKc_1,c_2,\ldots,c_K, each in the range 1N11\ldots N-1. If in the ii-th operation, FJ commands the cow facing him to move back cic_i steps, then after KK 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