博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
九度OJ 1146:Flipping Pancake(翻饼子) (递归、游戏)
阅读量:5076 次
发布时间:2019-06-12

本文共 2071 字,大约阅读时间需要 6 分钟。

时间限制:1 秒

内存限制:32 兆

特殊判题:

提交:265

解决:116

题目描述:

    We start with a stack n of pancakes of distinct sizes. The problem is to convert the stack to one in which the pancakes are in size order with the smallest on the top and the largest on the bottom. To do this, we are allowed to flip the top k pancakes over as a unit (so the k-th pancake is now on top and the pancake previously on top is now in the k-th position).

    For example: This problem is to write a program, which finds a sequence of at most (2n - 3) flips, which converts a given stack of pancakes to a sorted stack. 

输入:

    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. 

样例输入:
3 1 3 25 4 3 2 5 10
样例输出:
3 2 3 2 3 3 4 5
来源:

思路:

著名的翻饼子游戏。要求最后状态是小饼在大饼的上面,求翻得次数。最多需要翻2n-3次。

这种题要用逆向思维以及递归方法来分析,考察最终状态及前一步,逐步往前考察,从而发现游戏思路。

代码:

#include 
#define N 30 int n, k;int a[N+1], r[N+1], step[2*N+1]; void swap(int *x, int *y){ int tmp = *x; *x = *y; *y = tmp;} void print(int *x){ int j; for (j=1; j
=2; i--) { if (r[i] != i) { if (r[i] != 1) flip(r[i]); flip(i); } } printf("%d ", k); for (i=0; i

转载于:https://www.cnblogs.com/liangrx06/p/5083885.html

你可能感兴趣的文章
如何理解汉诺塔
查看>>
洛谷 P2089 烤鸡【DFS递归/10重枚举】
查看>>
15 FFT及其框图实现
查看>>
Linux基本操作
查看>>
osg ifc ifccolumn
查看>>
C++ STL partial_sort
查看>>
3.0.35 platform 设备资源和数据
查看>>
centos redis 安装过程,解决办法
查看>>
IOS小技巧整理
查看>>
WebDriverExtensionsByC#
查看>>
我眼中的技术地图
查看>>
lc 145. Binary Tree Postorder Traversal
查看>>
sublime 配置java运行环境
查看>>
在centos上开关tomcat
查看>>
重启rabbitmq服务
查看>>
正则表达式(进阶篇)
查看>>
无人值守安装linux系统
查看>>
【传道】中国首部淘宝卖家演讲公开课:农业本该如此
查看>>
jQuery应用 代码片段
查看>>
MVC+Servlet+mysql+jsp读取数据库信息
查看>>