汉诺塔合集之汉诺塔3

http://acm.hdu.edu.cn/showproblem.php?pid=2064

汉诺塔3:

步骤分析:

1.当只有一个圆盘时,要从a到b再到c;

2.同样扩展经典汉诺塔问题来看,先把a柱上(n-1)个圆盘,经b移动到c;

3.把最后一个圆盘从a移动到b;

4.把c柱上的(n-1)个圆盘,经b移动(移回)到a;

5.把b上的最后一个圆盘从b移到c;

6.最后把a上的(n-1)个圆盘经过b移动到c,over;

综上可看出(第2,4, 6步):

上面的(n-1)个圆盘来来回回跑了3趟;

最大的圆盘从a到b再到c(第3,5步);

so :   f[i] = 3 * f[i-1] + 2;

 1 /* */
 2 # include <bits/stdc++.h>
 3 # include <iostream>
 4 # include <cstdio>
 5 # include <cmath>
 6 using namespace std;
 7 
 8 int main()
 9 {
10     int i;
11     long long int f[40];
12     memset(f, 0, sizeof(f));
13     f[1] = 2;
14     for( i=2; i<=35; i++ )
15     {
16         f[i] = 3 * f[i-1] + 2;
17     }
18     int n;
19     while( ~ scanf("%d", &n) )
20     {
21         printf("%lld\n", f[n]);
22     }
23     return 0;
24 }

猜你喜欢

转载自www.cnblogs.com/wsy107316/p/10686273.html