HDUOJ----(2064)汉诺塔III

汉诺塔III

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 7934    Accepted Submission(s): 3483


Problem Description
约19世纪末,在欧州的商店中出售一种智力玩具,在一块铜板上有三根杆,最左边的杆上自上而下、由小到大顺序串着由64个圆盘构成的塔。目的是将最左边杆上的盘全部移到右边的杆上,条件是一次只能移动一个盘,且不允许大盘放在小盘的上面。
现在我们改变游戏的玩法,不允许直接从最左(右)边移到最右(左)边(每次移动一定是移到中间杆或从中间移出),也不允许大盘放到下盘的上面。
Daisy已经做过原来的汉诺塔问题和汉诺塔II,但碰到这个问题时,她想了很久都不能解决,现在请你帮助她。现在有N个圆盘,她至少多少次移动才能把这些圆盘从最左边移到最右边?
 
Input
包含多组数据,每次输入一个N值(1<=N=35)。
 
Output
对于每组数据,输出移动最小的次数。
 
Sample Input
1
3
12
 
Sample Output
2
26
531440
 
Author
Rabbit
 
Source
思路:
令不妨设dis表示盘子编号数(编号从上到下依次为1 2 3 4 5 ),n代表盘子数,cnt代表移动的次数
n=1     ans=2
dis=1    cnt=2;
 
n=2  6
dis=1  cnt=2;
dis=2  cnt=6;
 
n=3  26
dis=1  cnt=2; =2*3^0  (因为最右到最左需要走过3根柱子)
dis=2  cnt=6;  =2*3^1
dis=3  cnt=18 =2*3^2
ans=2*(3^n-1)/2 =3^n-1;
代码如下:
 1 #include<stdio.h>
 2 int main()
 3 {
 4     int n;
 5    _int64 cnt,ans;
 6     while(scanf("%d",&n)!=EOF)
 7     {
 8         cnt=3;
 9         ans=1;
10         while(n)
11         {
12             if(n&1)
13             {
14                 ans*=cnt;
15                 n--;
16             }
17             else
18             {
19                 cnt*=cnt;
20                 n>>=1;
21             }
22         }
23         ans--;
24         printf("%I64d
",ans);
25     }
26     return 0;
27 }
View Code
原文地址:https://www.cnblogs.com/gongxijun/p/3496599.html