HDU 4260 The End of The World (递推&递归) #by Plato

http://acm.hdu.edu.cn/showproblem.php?pid=4260

题意:给定hanoi塔的初始状态

求将所有的盘子移到B柱子上所要的步数。

Idea:

移动第n个盘子到B柱子,(前提是第n个盘子不在B柱子上,否则就处理第n-1个柱子)

1.将前n-1个移动到辅助的柱子上(递归/递推了)

2.将第n个盘子移到B上(+1)

3.将前n-1个移到B上(+2^(n-1)-1)


递归:

#include <cstdio>
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
char s[70];

long long cal(int n,char goal)
{
    char at;
    for (int i = n;i >= 1;i--)
    {
        if (s[i] != goal)
        {
            if (s[i] + goal == 'A'+ 'B') at = 'C';
            if (s[i] + goal == 'A' + 'C') at = 'B';
            if (s[i] + goal == 'B' + 'C') at = 'A';
            return cal(i-1,at)+(1LL<<i-1);//注意下运算顺序,这里要加括号
        }
    }
    return 0;
}

int main()
{
    freopen("test.txt","r",stdin);
    while (scanf("%s",s+1),s[1] != 'X')
    {
        int len = strlen(s+1);
        long long ans = cal(len,'B');
        printf("%I64d\n",ans);
    }

    return 0;
}

递推:

#include <cstdio>
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;

int main()
{
    freopen("test.txt","r",stdin);
    char s[70];
    int a[70];
    static long long f[70][4];
    memset(f,0,sizeof(f));
    while (scanf("%s",s+1),s[1] != 'X')
    {
        int len = strlen(s+1);
        for (int i = 1;i <= len;i++) a[i] = s[i] - 'A' +1;
        for (int i = 1;i <= len;i++)
        {
            for (int j = 1;j <= 3;j++)
            {
                if (a[i] == j)
                {
                    f[i][j] = f[i-1][j];
                }
                else
                {
                    f[i][j] = f[i-1][6-a[i]-j] + (1LL<<i-1);
                }
            }
        }

        printf("%I64d\n",f[len][2]);
    }

    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值