当前,这些奶牛以p1,p2,p3,…,pN的顺序排成一行,Farmer John站在奶牛p1前面。他想要重新排列这些奶牛,使得她们的顺序变为1,2,3,…,N,奶牛1在Farmer John旁边。
今天奶牛们有些困倦,所以任何时刻都只有直接面向Farmer John的奶牛会注意听Farmer John的指令。每一次他可以命令这头奶牛沿着队伍向后移动k步,k可以是1到N−1之间的任意数。她经过的k头奶牛会向前移动,腾出空间使得她能够插入到队伍中这些奶牛之后的位置。
例如,假设N=4,奶牛们开始时是这样的顺序:
FJ: 4, 3, 2, 1
唯一注意FJ指令的奶牛是奶牛4。当他命令她向队伍后移动2步之后,队伍的顺序会变成:
FJ: 3, 2, 4, 1
现在唯一注意FJ指令的奶牛是奶牛3,所以第二次他可以给奶牛3下命令,如此进行直到奶牛们排好了顺序。
Farmer John急欲完成排序,这样他就可以回到他的农舍里享用他自己的早餐了。请帮助他求出一个操作序列,使得能够用最少的操作次数将奶牛们排好顺序。
4 1 2 4 3
3 2 2 3
Currently, the cows are standing in a line in the order p1,p2,p3,…,pN, and Farmer John is standing in front of cow p1. He wants to reorder the cows so that they are in the order 1,2,3,…,N, with cow 1 next to Farmer John.
Today the cows are a bit sleepy, so at any point in time the only cow who is paying attention to Farmer John's instructions is the cow directly facing Farmer John. In one time step, he can instruct this cow to move k paces down the line, for any k between 1 and N−1 inclusive. The k cows whom she passes will amble forward, making room for her to insert herself in the line after them.
For example, suppose that N=4 and the cows start off in the following order:
FJ: 4, 3, 2, 1
The only cow paying attention to FJ is cow 4. If he instructs her to move 2 paces down the line, the order will subsequently look like this:
FJ: 3, 2, 4, 1
Now the only cow paying attention to FJ is cow 3, so in the second time step he may give cow 3 an instruction, and so forth until the cows are sorted.
Farmer John is eager to complete the sorting, so he can go back to the farmhouse for his own breakfast. Help him find a sequence of instructions that sorts the cows in the minimum number of time steps.
4 1 2 4 3
3 2 2 3
4
1 2 4 3
3
2 2 3