HDU 2511.漢諾塔 X

題目:http://acm.hdu.edu.cn/showproblem.php?pid=2511

AC代碼(C++):

#include <iostream>
#include <queue>
#include <set>
#include <string>
#include <algorithm>
#include <string.h>
#include <math.h>

#define INF 0x3f3f3f3f
#define eps 1e-8
typedef unsigned long long ULL;

using namespace std;

void Hanoi(int n, ULL m, int from, int mid, int to) {
    ULL step = ((ULL)1 << (n - 1)) - 1;
    if (m <= step)Hanoi(n - 1, m, from, to, mid);
    else if (m == step + 1)cout << n << ' ' << from << ' ' << to << endl;
    else Hanoi(n - 1, m-1-step, mid, from, to);
}

int main() {
    int t;
    cin >> t;
    while (t--) {
        int n;
        ULL m;
        cin >> n >> m;
        Hanoi(n, m, 1, 2, 3);
    }

    //system("pause");
}
總結: 做這題首先要了解漢諾塔(Hanoi Tower)是怎麼運作的. 要解決規模爲n(即n層)的漢諾塔問題, 可以把問題分爲三個階段. 第一階段, 把n-1個盤子放到mid上; 第二階段, 把第n個盤子放到to上; 第三階段, 把mid上的n-1個盤子放到to上. 而第一和第三階段都是遞歸完成的, 而解決一次遞歸只需要第二階段的1次移動, 所以規模爲n的漢諾塔問題移動次數爲2^n-1次. 故第一和第三階段都只需移動2^(n-1)-1次. 那麼對於一個輸入m, 如果m小於等於2^(n-1)-1, 就說明這一步屬於解決n規模問題的第一階段, 如果m等於2^(n-1)-1+1, 則說明處於第二階段, 可以直接得到答案, 如果大於2^(n-1)-1+1, 則說明在第三階段. 那麼在第一第三階段的直接遞歸解決就好了.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章