zoukankan      html  css  js  c++  java
  • 3145 汉诺塔游戏——http://codevs.cn/problem/3145/

    第一部分:题目

    题目描述 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

    第二部分:思路

    这里使用的是递归。想象一下,要把一个盘子从A->C,只需要一步:1 from A to C.把2个盘子从A->C:要先把2从A->B,然后把1从A->C,最后把2从B->C;规律就是:当N>1时,先把N-1个上面的盘子移到目标柱子的另外一个柱子(这里称为 伪目标柱子),然后把N从当前柱子移到目标柱子,最后把N-1个盘子从伪目标柱子移到目标柱子。从这里可以得出,最少步骤等于2的n次方减1.

    第三部分:代码

    /*
    将n个盘子从A移动到C可分解为下面3个步骤:
    1、将A上n-1个盘子移到B上(借助C)
    2、将A上剩下的一个盘子移到C上
    3、将n-1个盘子从B移到C上(借助A)
    */
    #include<iostream>
    using namespace std;
    void move(char src, char dest){
        cout << src << "-->" << dest << endl;
    }
    void hanoi(int n, char src, char medium, char dest){
        if (n == 1){
            move(src, dest);
        }
        else{
            hanoi(n - 1, src, dest, medium);
            move(src, dest);
            hanoi(n - 1, medium, src, dest);
        }
    }
    void run(){
        int n;
        cout << "请输入汉诺塔的层数" << endl;
        cin >> n;
        system("cls");
        cout <<n<<"层移动步骤是:" << endl;
        hanoi(n, 'A', 'B', 'C');
    }
    int main(){
        int flag;
        do{
            run();
            cout << "1继续,0退出" << endl;
            cin >> flag;
        } while (flag == 1);
        return 0;
    }
  • 相关阅读:
    How to convert VirtualBox vdi to KVM qcow2
    (OK)(OK) adb -s emulator-5554 shell
    (OK)(OK) using adb with a NAT'ed VM
    (OK) How to access a NAT guest from host with VirtualBox
    (OK) Creating manually one VMs from an existing VDI file in CLI (VBoxManage) in Fedora 23
    (OK)(OK) Creating VMs from an existing VDI file in CLI (VBoxManage) in Fedora 23
    (OK) Creating_VMs_from_an_existing_VDI_file.txt
    (OK) Creating VMs from an existing VDI file —— in OS X
    (OK) install_IBM_SERVER.txt
    (OK) install chrome & busybox in android-x86_64 —— uninstall chrome
  • 原文地址:https://www.cnblogs.com/xiangguoguo/p/5343019.html
Copyright © 2011-2022 走看看