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;
}


你可能感兴趣的:(c,idea)