Flipping Pancake

查看题解 查看答案
题目描述
Time Limit: 1000 ms
Memory Limit: 256 mb

请先登录再刷题,不会做的题目右上可以查看题解和答案~

输入输出格式
输入描述:
Each line of the input gives a separate data set as a sequence of numbers separated by spaces. The first number on each line gives the number, N, of pancakes in the data set. The input ends when N is 0 (zero) with no other data on the line. The remainder of the data set are the numbers 1 through N in some order giving the initial pancake stack.

The numbers indicate the relative sizes of the pancakes. N will be, at most, 30.
输出描述:
For each data set, the output is a single-space separated sequence of numbers on a line. The first number on each line, K, gives the number of flips required to sort the pancakes. This number is followed by a sequence of K numbers, each of which gives the number of pancakes to flip on the corresponding sorting step. There may be several correct solutions for some datasets. For instance 3 3 2 3 is also a solution to the first problem below.
输入输出样例
输入样例#:
2 2 1
6 2 5 6 1 3 4
0
输出样例#:
复制
1 2
4 3 6 4 2
提示
关于Pancake sorting的一种简单情况。就是有种方法可以保证至多2n-3次完成。

类似于选择排序:
先找出n各数字种最大的一个数n,假设所在位置为sn,那么先翻转前sn个数字f(sn),
使得n在最顶部,之后再翻转前n个元素f(n),这样一来n就到了最底部。就是两次翻转。
之后再选择第二大的假设为n-1,位置在sn-1,那么先翻转前sn-1个数字f(sn-1),使得n-1在最
顶部,之后再翻转前n-1个元素f(n-1),这样一来n-1就到了倒数第二个。也是两次翻转。
注意:每次对于第x大的元素要判断它是不是在倒是第x个位置上,若在就不用翻转这个数字了。
一直进行n-2次,最多2n-4次翻转。剩下上面三个最小的1,2其它的都排序了。

分成2种情况,顶多1次搞定:
12:已经有序,不用翻转。
21:一次,f(2)
题目来源
北京大学机试题
重置

提交代码后在此处可查看状态