boj 1343汉诺塔 递归问题 多谢大牛的代码和讲解 我需要多联系类似题目

地址:http://acm.scs.bupt.cn/onlinejudge/showproblem.php?problem_id=1343

 

Tower of Hanoi Submit: 115    Accepted:31 Time Limit: 1000MS  Memory Limit: 65535K

Description
The Tower of Hanoi is a puzzle consisting of three pegs(namead 1,2,3) and a number of disks of different sizes which can slide onto any peg. The puzzle starts with the disks neatly stacked in order of size on one peg(1), the smallest at the top, thus making a conical shape. The objective of the puzzle is to move the entire stack to another peg(3), obeying the following rules:
Only one disk may be moved at a time.
Each move consists of taking the upper disk from one of the pegs and sliding it onto another peg, on top of the other disks that may already be present on that peg.
No disk may be placed on top of a smaller disk.
For n disks, it is a well-known result that the optimal solution takes 2^n− 1 moves.
Sunny has a YuGong’s spirit, he want to do this day by day by day …... So , he make a tower of hanoi which has n (n<=31) disks , and just wrote down the number of steps he moved before , and this day , he wants to move the ith step to jth step(1<=i<=j<2^n&&j-i<=50) . Now , please tell him each of step he should do .


Input
The first line contains only one integer k , the number of cases.
Each of test case only one line contains three integers n, i , j .


Output
For each test case , first line print “Case d:” , means the dth case.
Next j-i+1 lines print “b->e”, (b,e=1,2,3) , which means move a disk from b peg to e peg .


Sample Input

2
2 1 3
3 1 4


Sample Output

Case 1:
1->2
1->3
2->3
Case 2:
1->3
1->2
3->2
1->3

 

 

 

#include <stdio.h>

// 将N个盘子由Src移动到第Dst根柱子,并输出其中的第i->j步
void Move(int N, int Src, int Dst, int i, int j)
{
   
int Step = (1 << (N - 1)) - 1; // 计算将N-1个盘子移到中间柱子的所需步数
    if (N > 1 && i <= Step)        // 如果这个过程中覆盖到了第i->j步,则递归进去,否则没必要
    {
        Move(N
- 1, Src, 6 - Src -Dst, i, j);
    }

   
++Step;
   
if (i <= Step && Step <= j)     // 最底下一个盘子移动到目标
    {
        printf(
"%d->%d/n", Src, Dst);
    }

   
// 将N-1个盘子由中间柱子移动到目标柱子
    if (N > 1 && j > Step)          // 如果这个过程中覆盖到了第i->j步,则递归进去,否则没必要
    {
        Move(N
- 1, 6 - Src - Dst, Dst, i - Step, j - Step);
    }
}

int main()
{
   
int TotalCases;
    scanf(
"%d", &TotalCases);

   
for (int Case = 1; Case <= TotalCases; ++Case)
    {
       
int n, i, j;
        scanf(
"%d %d %d", &n, &i, &j);
        printf(
"Case %d:/n", Case);
        Move(n,
1, 3, i, j);
    }
   
return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值