Strange Towers of Hanoi (POJ1958)
Strange Towers of Hanoi (POJ1958)
n个盘子4座塔的Hanoi问题至少需要多少步?(1<=n<=12)
分析:
n盘3塔: \(d[n] = 2*d[n-1]+1\) => \(d[n] = 2^n - 1\)
- 前n-1盘子 A -> B
- 第n盘子 A -> C
- 前n-1盘子 B -> C
n盘4塔:\(f[n] = min_{1\leq i<n}\{2*f[i] + d[n-i]\}\)
- 把i个盘子 A->B (四塔模式)
- 把n-i个盘子 A->D (三塔模式)
- 把i个盘子 B-> D (四塔模式)
- 考虑所有可能i取最小值
题解:
#include<iostream> #include<cmath> using namespace std; int main(){ int f[13] = {0}; int minstep,step; f[1] = 1; for(int n=2;n<=12;n++){ minstep = 0x3f3f3f3f; step=0; for(int i=1;i<n;i++){ step = 2*f[i] + pow((float)2,n-i)-1; //POJ C++的pow格式严格 if(step<minstep) minstep = step; } f[n] = minstep; } for(int n=1;n<=12;n++){ cout<<f[n]<<endl; } return 0; }
转载于//www.cnblogs.com/wendiudiu/p/10762157.html
还没有评论,来说两句吧...