UVa 254 - Towers of Hanoi 解题报告(递归)

56 篇文章 0 订阅

 Towers of Hanoi 

In 1883, Edouard Lucas invented, or perhaps reinvented, one of the most popular puzzles of all times - the Tower of Hanoi, as he called it - which is still used today in many computer science textbooks to demonstrate how to write a recursive algorithm or program. First of all, we will make a list of the rules of the puzzle:

  • There are three pegs: AB and C.
  • There are n disks. The number n is constant while working the puzzle.
  • All disks are different in size.
  • The disks are initially stacked on peg A so that they increase in size from the top to the bottom.
  • The goal of the puzzle is to transfer the entire tower from the A peg to one of the others pegs.
  • One disk at a time can be moved from the top of a stack either to an empty peg or to a peg with a larger disk than itself on the top of its stack.

A good way to get a feeling for the puzzle is to write a program which will show a copy of the puzzle on the screen and let you simulate moving the disks around. The next step could be to write a program for solving the puzzle in a efficient way. You don't have to do neither, but only know the actual situation after a given number of moves by using a determinate algorithm.

The Algorithm

It is well known and rather easy to prove that the minimum number of moves needed to complete the puzzle with n disks istex2html_wrap_inline44 . A simple algorithm which allows us to reach this optimum is as follows: for odd moves, take the smallest disk (number 1) from the peg where it lies to the next one in the circular sequence tex2html_wrap_inline46 ; for even moves, make the only possible move not involving disk 1.

Input

The input file will consist of a series of lines. Each line will contain two integers nmn, lying within the range [0,100], will denote the number of disks and m, belonging to [0, tex2html_wrap_inline44 ], will be the number of the last move. The file will end at a line formed by two zeros.

Output

The output will consist again of a series of lines, one for each line of the input. Each of them will be formed by three integers indicating the number of disks in the pegs AB and C respectively, when using the algorithm described above.

Sample Input

3 5
64 2
8 45
0 0

Sample Output

1 1 1
62 1 1
4 2 2

    解题报告:算是思维题。让我们求出汉诺塔移动m步之后,三根柱子上各有多少个盘子。

    我们还是可以按照类似于解决汉诺塔的方法思考这个问题。考虑当前最大的盘子n。如果当前要移动的步骤数m小于等于把n以上的n-1个盘子移动到临时柱子的步骤数2^(n-1)-1,那么n盘不需要移动,n盘所在柱子的盘子数+1,继续移动n-1盘m步;否则步骤数减去2^(n-1),移动n盘到目标位置,目标位置盘子数+1,此时1到n-1的所有盘都在临时柱子上,我们移动n-1盘m-2^(n-1)步。递归下去。

    注意两点:一是题目中的移动方法,n为奇数时目标盘是2,偶数时目标盘为3。二是n比较大,需要用到大数。当然,java就方便了。

    代码如下:

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <queue>
#include <vector>
#include <map>
#include <set>
#include <string>
#include <iomanip>
using namespace std;
#define ff(i, n) for(int i=0;i<(n);i++)
#define fff(i, n, m) for(int i=(n);i<=(m);i++)
#define dff(i, n, m) for(int i=(n);i>=(m);i--)
#define bit(n) (1LL<<(n))
typedef long long LL;
typedef unsigned long long ULL;
void work();
int main()
{
#ifdef ACM
    freopen("in.txt", "r", stdin);
#endif // ACM
    work();
}

/***************************************************/

const int K = 10000;    // 数组里每位代表1W
const int M = 10;       // 一共10位
const char show[] = "%04lld";

struct Bignum
{
    LL a[M*2];          // 大数数组
    int len;            // 长度
    bool negative;      // 正负

    Bignum()
    {
        clear();
    }

    void clear()
    {
        len=0;
        negative=false;
        memset(a, 0, sizeof(a));
    }

    Bignum(LL num)
    {
        *this=num;
    }

    Bignum(char * str)
    {
        *this=str;
    }

    Bignum operator=(LL num)
    {
        clear();
        if(num<0) negative=true, num=-num;
        while(num)
            a[len++]=num%K,num/=K;
        return *this;
    }

    Bignum operator=(char * str)
    {
        clear();
        if(str[0] == '-')
            negative = true, str++;

        int l = strlen(str);

        int width = (int)log10(K + 0.5);
        int idx = 0;
        dff(i, l-1, 0)
        {
            if(idx == width) idx=0, len++;
            a[len] = a[len] + (str[i]-'0')*pow(10, idx);
            idx++;
        }

        len++;
    }

    Bignum(const Bignum& cmp)
    {
        memcpy(this, &cmp, sizeof(Bignum));
    }

    Bignum operator=(const Bignum& cmp)
    {
        memcpy(this, &cmp, sizeof(Bignum));
        return *this;
    }

    int absCmp(const Bignum& cmp)
    {
        if(len!=cmp.len)
            return len>cmp.len?1:-1;

        for(int i=len-1;i>=0;i--)
            if(a[i]!=cmp.a[i])
                return a[i]>cmp.a[i]?1:-1;

        return 0;
    }

    int absCmp(LL num)
    {
        Bignum cmp(num);
        return absCmp(cmp);
    }

    bool operator<(const Bignum& cmp)
    {
        if(negative^cmp.negative)
            return negative?true:false;

        if(negative)
            return absCmp(cmp)>0;
        else
            return absCmp(cmp)<0;
    }

    bool operator<(LL num)
    {
        Bignum cmp(num);
        return *this<cmp;
    }

    bool operator==(const Bignum& cmp)
    {
        if(negative^cmp.negative)
            return false;
        return absCmp(cmp)==0;
    }

    bool operator==(LL num)
    {
        Bignum cmp(num);
        return *this==cmp;
    }

    void absAdd(const Bignum& one, const Bignum& two)
    {
        len=max(one.len, two.len);
        for(int i=0;i<len;i++)
        {
            a[i]+=one.a[i]+two.a[i];
            if(a[i]>=K) a[i]-=K, a[i+1]++;
        }
        if(a[len]) len++;
    }

    void absSub(const Bignum& one, const Bignum& two)
    {
        len=one.len;
        for(int i=0;i<len;i++)
        {
            a[i]+=one.a[i]-two.a[i];
            if(a[i]<0) a[i+1]--,a[i]+=K;
        }
        while(len>0 && a[len-1]==0) len--;
    }

    void absMul(const Bignum& one, const Bignum& two)
    {
        len=one.len+two.len;
        for(int i=0;i<one.len;i++) for(int j=0;j<two.len;j++)
            a[i+j]+=one.a[i]*two.a[j];
        for(int i=0;i<len;i++) if(a[i]>=K)
            a[i+1]+=a[i]/K,a[i]%=K;
        while(len>0 && a[len-1]==0) len--;
    }

    Bignum operator+(const Bignum& cmp)
    {
        Bignum c;
        if(negative^cmp.negative)
        {
            bool res = absCmp(cmp)>0;
            c.negative = !(negative^res);
            if(res)
                c.absSub(*this, cmp);
            else
                c.absSub(cmp, *this);
        }
        else if(negative)
        {
            c.negative=true;
            c.absAdd(*this, cmp);
        }
        else
        {
            c.absAdd(*this, cmp);
        }
        return c;
    }

    Bignum operator-(const Bignum& cmp)
    {
        Bignum cpy;
        if(cpy==cmp)
            return *this;
        else
            cpy=cmp, cpy.negative^=true;

        return *this+cpy;
    }

    Bignum operator*(const Bignum& cmp)
    {
        Bignum c;
        if(c==cmp || c==*this)
            return c;

        c.negative = negative^cmp.negative;
        c.absMul(*this, cmp);
        return c;
    }

    void output()
    {
        if(len==0)
        {
            puts("0");
            return;
        }

        if(negative)
            printf("-");

        printf("%lld", a[len-1]);
        for(int i=len-2;i>=0;i--)
            printf(show, a[i]);
        puts("");
    }
};

int peg[4];
Bignum two[111];
char str[111];

void dfs(int n, int sta, int end, Bignum m)
{
    if(n == 0) return;

    if(m < two[n-1])
    {
        peg[sta]++;
        dfs(n-1, sta, 6-sta-end, m);
    }
    else
    {
        peg[end]++;
        dfs(n-1, 6-sta-end, end, m - two[n-1]);
    }
}

void work()
{
    two[0] = 1;
    fff(i, 1, 100)
        two[i] = two[i-1]*2;

    int n;
    while(scanf("%d%s", &n, str) == 2 && (n||str[0]!='0'))
    {
        memset(peg, 0, sizeof(peg));

        Bignum m = str;
        dfs(n, 1, n%2 ? 2 : 3, m);
        printf("%d %d %d\n", peg[1], peg[2], peg[3]);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值