P_191Hanoi塔问题

用递归的方法:

    1、将n-1个盘从一个座移到另一个座,

    2、将1一个盘从一个座移到另一个座。

      (a、将A上n-1个盘借助C移到B)

      (b、将A上最后一个移到C上)

      (c、将n-1个盘从B借助A移到C上)。

 1 #include<iostream>
 2 
 3 using namespace std;
 4 
 5 void hanoi(int n, char one, char two, char three)//n个盘子从one移到three(借助two)
 6 {
 7     int count = 0;
 8     void move(char x, char y);
 9     if (n == 1)
10         move(one, three);
11     else
12     {
13         hanoi(n - 1, one, three, two);//n-1个盘子从one移到two
14         move(one, three);             //n=1,直接把one 移到three
15         hanoi(n - 1, two, one, three);//n-1个盘子在从two移到three
16     }
17 }
18 
19 void move(char x, char y)
20 {
21     cout << x << "-->" << y << endl;
22 }
23 
24 int main()
25 {
26     void hanoi(int n, char one, char two, char three);
27     int m;      //输入多少个盘子
28     cin >> m;
29     hanoi(m, 'A', 'B', 'C');
30     system("pause");
31     return 0;
32 }

 1 /*描述:
 2 包含多组数据,首先输入T,表示有T组数据.每个数据一行,
 3 是盘子的数目N(1<=N<=60)和盘号k(1<=k<=N)。
 4 Output 
 5 对于每组数据,输出一个数,到达目标时k号盘需要的最少移动数。
 6 n个盘子,编号为k的盘子的移动次数=pow(2,n-k);*/
 7 #include<iostream>
 8 #include<cmath>
 9 
10 using namespace std;
11 
12 int main()
13 {
14     int t,n,k;
15     cin>>t;
16     while(t--)
17     {
18         cin>>n>>k;//圆盘和盘号
19         cout<<(long long)pow(2.0,n-k)<<endl; //最少移动次数,k=1时,全移动 
20     }
21     return 0;
22  } 

转载请说明出处!
原文地址:https://www.cnblogs.com/zengshangzhi/p/8780810.html