题目入口
这一题我就感觉没有那么简单,刚上手就直接超时了,后来想着应该是打表找规律,后来补题看题解是用记忆化搜索说实话,我看了半天而且还了解了解什么是重载,心态有点崩了。其实好理解就是开一个结构体类型的数组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);
}