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
    评论
好的,我了解你的要求,不会透露给别人,也不会重复你的话。关于Hanoi塔问题的图形版程序,你需要使用图形界面库来实现可视化操作,比如使用Python中的Tkinter库。以下是一个简单的代码示例,可以让你更好地理解如何实现这个程序。需要注意的是,这个程序只是一个简单的示例,你可以根据自己的需求对其进行修改和优化。 ```python import tkinter as tk import time class TowerOfHanoi: def __init__(self, n): self.n = n self.towers = [[i for i in range(n, 0, -1)], [], []] self.moves = [] def move(self, start, end): disk = self.towers[start].pop() self.towers[end].append(disk) self.moves.append((start, end)) def solve(self): self.moves = [] self.recursive_solve(self.n, 0, 2, 1) return self.moves def recursive_solve(self, n, start, end, aux): if n == 1: self.move(start, end) else: self.recursive_solve(n-1, start, aux, end) self.move(start, end) self.recursive_solve(n-1, aux, end, start) class TowerOfHanoiGUI: def __init__(self, master, n): self.master = master self.n = n self.width = 600 self.height = 400 self.padding = 30 self.colors = ["red", "green", "blue"] self.disk_width = 120 self.disk_height = 20 self.tower_width = 10 self.tower_height = 200 self.delay = 1000 self.speed = 1 self.canvas = tk.Canvas(master, bg="white", width=self.width, height=self.height) self.canvas.pack() self.towers = [self.canvas.create_rectangle(self.padding + i * (self.width - 2 * self.padding) / 3 - self.tower_width / 2, self.height - self.padding - self.tower_height, self.padding + i * (self.width - 2 * self.padding) / 3 + self.tower_width / 2, self.height - self.padding, fill=self.colors[i]) for i in range(3)] self.disks = [[self.canvas.create_rectangle(self.padding + i * (self.width - 2 * self.padding) / 3 - self.n * self.disk_width / 2 + j * self.disk_width / self.n, self.height - self.padding - self.tower_height + (self.n - i - 1) * self.disk_height, self.padding + i * (self.width - 2 * self.padding) / 3 - self.n * self.disk_width / 2 + (j + 1) * self.disk_width / self.n, self.height - self.padding - self.tower_height + (self.n - i) * self.disk_height, fill=self.colors[i]) for j in range(i + 1)] for i in range(self.n)] self.moves = TowerOfHanoi(self.n).solve() self.index = 0 self.paused = False self.button = tk.Button(master, text="Pause", command=self.toggle_pause) self.button.pack(side=tk.TOP) self.speed_scale = tk.Scale(master, from_=1, to=10, orient=tk.HORIZONTAL, command=self.set_speed) self.speed_scale.set(self.speed) self.speed_scale.pack(side=tk.TOP) def toggle_pause(self): self.paused = not self.paused self.button.configure(text="Resume" if self.paused else "Pause") def set_speed(self, speed): self.speed = int(speed) def run(self): while self.index < len(self.moves): start, end = self.moves[self.index] disk = self.towers[start] x0, y0, x1, y1 = self.canvas.coords(disk) while y1 < self.height - self.padding: if not self.paused: self.canvas.move(disk, 0, self.speed) self.canvas.update() time.sleep(self.delay / 1000) x0, y0, x1, y1 = self.canvas.coords(disk) else: time.sleep(0.1) self.canvas.move(disk, (end - start) * (self.width - 2 * self.padding) / 3, 0) self.canvas.update() time.sleep(self.delay / 1000) self.index += 1 def main(): n = 4 root = tk.Tk() gui = TowerOfHanoiGUI(root, n) gui.run() root.mainloop() if __name__ == "__main__": main() ``` 这个程序使用Tkinter库创建了一个简单的GUI界面,其中有三个塔座和n个不同大小的圆盘。当程序运行时,它会自动求解Hanoi塔问题,并将每个圆盘从一个塔座移动到另一个塔座。用户可以通过暂停/继续按钮暂停或继续动画,并使用速度滑块调整动画速度。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值