zoukankan      html  css  js  c++  java
  • 3145 汉诺塔游戏

    3145 汉诺塔游戏

     

     时间限制: 1 s
     空间限制: 32000 KB
     题目等级 : 白银 Silver
     
     
    题目描述 Description

    汉诺塔问题(又称为河内塔问题),是一个大家熟知的问题。在A,B,C三根柱子上,有n个不同大小的圆盘(假设半径分别为1-n吧),一开始他们都叠在我A上(如图所示),你的目标是在最少的合法移动步数内将所有盘子从A塔移动到C塔。

    游戏中的每一步规则如下:

    1. 每一步只允许移动一个盘子(从一根柱子最上方到另一个柱子的最上方)

    2. 移动的过程中,你必须保证大的盘子不能在小的盘子上方(小的可以放在大的上面,最大盘子下面不能有任何其他大小的盘子)

    如对于n=3的情况,一个合法的移动序列式:

    1 from A to C

    2 from A to B

    1 from C to B

    3 from A to C

    1 from B to A

    2 from B to C

    1 from A to C

    给出一个数n,求出最少步数的移动序列

    输入描述 Input Description

    一个整数n

    输出描述 Output Description

    第一行一个整数k,代表是最少的移动步数。

    接下来k行,每行一句话,N from X to Y,表示把N号盘从X柱移动到Y柱。X,Y属于{A,B,C}

    样例输入 Sample Input

    3

    样例输出 Sample Output

    7

    1 from A to C

    2 from A to B

    1 from C to B

    3 from A to C

    1 from B to A

    2 from B to C

    1 from A to C

    数据范围及提示 Data Size & Hint

    n<=10

     1 #include<iostream>
     2 #include<cstdio>
     3 #include<queue>
     4 using namespace std;
     5 int tot=0;
     6 void ha1(int n,char a,char c,char b)
     7 {
     8     if(n==0)return;
     9     ha1(n-1,a,b,c);
    10     tot++;
    11     ha1(n-1,b,c,a);
    12 }
    13 void ha2(int n,char a,char c,char b)
    14 {
    15     if(n==0)return;
    16     ha2(n-1,a,b,c);
    17     tot++;
    18     cout<<n<<" from"<<" "<<(char)(a-32)<<" "<<"to"<<" "<<(char)(c-32)<<" "<<endl;
    19     ha2(n-1,b,c,a);
    20 }
    21 int main()
    22 {
    23     int n;
    24     cin>>n;
    25     ha1(n,'a','c','b');
    26     cout<<tot<<endl;
    27     tot=0;
    28     ha2(n,'a','c','b');
    29     return 0;
    30 }
  • 相关阅读:
    swoole创建进程
    php中,posix_getpid() 和 getmypid() 有什么不同
    php查看进程
    初探PHP多进程
    nginx转发
    mime类型
    acwing 517. 信息传递
    LeetCode 1255 得分最高的单词集合 Maximum Score Words Formed by Letters
    LEETCODE 1254 统计封闭岛屿的数目 Number of Closed Islands
    算法问题实战策略 SORTGAME
  • 原文地址:https://www.cnblogs.com/zwfymqz/p/6489436.html
Copyright © 2011-2022 走看看