标签:space iii highlight set ios 递归 names else mes
上实验课随手水一波汉诺塔III#include<iostream>
#include<iostream> #include<cstring> #define LL long long #define N 40 using namespace std; LL f[4][4][4][N]; LL solve(int a,int b,int c,int n){ if(n == 0) return 0; if(f[a][b][c][n]) return f[a][b][c][n]; if(n == 1){ if(a == 2 || b == 2) return f[a][b][c][n] = 1; else return f[a][b][c][n] = 2; } else if(a == 2){ return f[a][b][c][n] = solve(a,c,b,n-1) + 1 + solve(c,a,b,n-1) + solve(a,b,c,n-1); } else if(b == 2){ return f[a][b][c][n] = solve(a,b,c,n-1) + solve(b,c,a,n-1) + 1 + solve(c,b,a,n-1); } else{ return f[a][b][c][n] = solve(a,c,b,n-1) + solve(c,b,a,n-1) + 1 + solve(b,c,a,n-1) + solve(c,a,b,n-1) + 1 + solve(a,c,b,n-1) + solve(c,b,a,n-1); } } int main(){ int n; while(cin >> n){ cout << solve(1,3,2,n) << endl; memset(f,0,sizeof(f)); } return 0; }
主要加个记忆化即可,写成递归也行吧。。。
标签:space iii highlight set ios 递归 names else mes
原文地址:http://www.cnblogs.com/woodenhead/p/7992150.html