HDU 2511 汉诺塔X

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2511

1,2,...,n表示n个盘子.数字大盘子就大.n个盘子放在第1根柱子上.大盘不能放在小盘上.在第1根柱子上的盘子是a[1],a[2],...,a[n]. a[1]=n,a[2]=n-1,...,a[n]=1.即a[1]是最下面的盘子.把n个盘子移动到第3根柱子.每次只能移动1个盘子,且大盘不能放在小盘上.问第m次移动的是哪一个盘子,从哪根柱子移到哪根柱子.例如:n=3,m=2. 回答是 :2 1 2,即移动的是2号盘,从第1根柱子移动到第2根柱子 。 

Input第1行是整数T,表示有T组数据,下面有T行,每行2个整数n (1 ≤ n ≤ 63) ,m≤ 2^n-1 
Output输出第m次移动的盘子号数和柱子的号数. 
Sample Input

4
3 2
4 5
39 183251937942
63 3074457345618258570

Sample Output

2 1 2
1 3 1
2 2 3
2 2 3

模拟(+递归)盘子移动的过程:
   1.如果m=a[n-1]+1,即刚好移动n号盘子,移动方向A-->C
   2.如果m>a[n-1],则考虑n-1号盘子,移动方向是B-->C,移动次数是m-(a[n-1]+1)
   3.如果m<=a[n-1],考虑n-1个盘子,移动方向是A-->B,移动次数是m;
   4.重复1,2,3点

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <cstring>
 4 #include <cstdio>
 5 #include <vector>
 6 #include <cstdlib>
 7 #include <iomanip>
 8 #include <cmath>
 9 #include <ctime>
10 #include <map>
11 #include <set>
12 #include <queue>
13 using namespace std;
14 #define lowbit(x) (x&(-x))
15 #define max(x,y) (x>y?x:y)
16 #define min(x,y) (x<y?x:y)
17 #define MAX 100000000000000000
18 #define MOD 1000000007
19 #define pi acos(-1.0)
20 #define ei exp(1)
21 #define PI 3.141592653589793238462
22 #define INF 0x3f3f3f3f3f
23 #define mem(a) (memset(a,0,sizeof(a)))
24 typedef long long ll;
25 ll gcd(ll a,ll b){
26     return b?gcd(b,a%b):a;
27 }
28 bool cmp(int x,int y)
29 {
30     return x>y;
31 }
32 const int N=10005;
33 const int mod=1e9+7;
34 int n;
35 ll m,a[64];
36 void hanio(int x,int y,int z,int n,ll m)
37 {
38     if(m==a[n-1]+1){
39         printf("%d %d %d
",n,x,z);
40         return ;
41     }
42     if(m>a[n-1]) hanio(y,x,z,n-1,m-a[n-1]-1);
43     if(m<=a[n-1]) hanio(x,z,y,n-1,m);
44 }
45 int main()
46 {
47     int t,i;
48     scanf("%d",&t);
49     a[1]=1;
50     for(i=2;i<=63;i++) {
51         a[i]=2*a[i-1]+1;
52     }
53     while(t--){
54         scanf("%d%lld",&n,&m);
55         hanio(1,2,3,n,m);
56     }
57     return 0;
58 }
原文地址:https://www.cnblogs.com/shixinzei/p/7297985.html