牛牛的汉诺塔(记忆化搜索)

题目入口
这一题我就感觉没有那么简单,刚上手就直接超时了,后来想着应该是打表找规律,后来补题看题解是用记忆化搜索说实话,我看了半天而且还了解了解什么是重载,心态有点崩了。其实好理解就是开一个结构体类型的数组dp【5】【5】【5】【105】,分别记录路径,如果有的话直接返回结果,说实话要自己多打几遍可能才能懂。
原题的代码如下:

#include<bits/stdc++.h>
using namespace std;
const int N=1e5+5;
const int mod=1e9+7;
const int INF=0x3f3f3f3f;
const double EPS=1e-6;
typedef long long ll;
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define int long long
struct node
{
    ll data[6]={0};
};
node operator + (const node &A,const node &B)//重载运算符
{
    node C;//就是为了让两个结构体数字相加
    for(int i=0;i<6;++i)
    {
        C.data[i]=A.data[i]+B.data[i];
    }
    return C;
}
node dp[5][5][5][100];
int vis[5][5][5][100];//记忆化数组,如果为1则已经标记可以直接使用
void move(int x,int y,node &temp)//记录每一步移动的结果
{
    if(x==0&&y==1)++temp.data[0];
    if(x==0&&y==2)++temp.data[1];
    if(x==1&&y==0)++temp.data[2];
    if(x==1&&y==2)++temp.data[3];
    if(x==2&&y==0)++temp.data[4];
    if(x==2&&y==1)++temp.data[5];
    return ;
}
node hanoi(int a,int b,int c,int n)
{
    if(vis[a][b][c][n])
        return dp[a][b][c][n];
    if(n==1)
    {
        move(a,c,dp[a][b][c][n]);
        vis[a][b][c][n]=1;
        return dp[a][b][c][n];
    }
    node temp;
    temp=temp+hanoi(a,c,b,n-1);
    move(a,c,temp);
    temp=temp+hanoi(b,a,c,n-1);
    vis[a][b][c][n]=1;
    return dp[a][b][c][n]=temp;
}
signed main()
{
    IOS;
    //freopen("","r",stdin);
    //freopen("","w",stdout);
    int n;
    cin>>n;
    node ans=hanoi(0,1,2,n);
    printf("A->B:%lld\n",ans.data[0]);
    printf("A->C:%lld\n",ans.data[1]);
    printf("B->A:%lld\n",ans.data[2]);
    printf("B->C:%lld\n",ans.data[3]);
    printf("C->A:%lld\n",ans.data[4]);
    printf("C->B:%lld\n",ans.data[5]);
    printf("SUM:%lld\n",(1LL<<n)-1);
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值