解題思路
灰環不能放在同大小白環上,因此所有環的合法堆疊次序等價於編號由小到大的標準漢諾塔。
從最大環n往下處理,目的柱為偶數C、奇數B。若最大環已在目的柱,遞迴處理較小環;否則先用標準漢諾塔將全部較小環移到第三柱,再移最大環,最後從第三柱處理較小環的指定終態。
從整疊角點出發到指定終態,移動最大環前較小環必須全在第三柱,因此上述必要操作與最短標準搬移組合,給出最短路徑。奇數輸入先輸出ERROR。
輸出步數為指數規模,時間 Θ(步數),遞迴空間 O(N),計數任意精度。
Step-by-step animation
教學小例:標準漢諾塔順序到指定終態
步驟 1 / 3
N=2
先將環1由A到B
先將環1由A到B
- 步驟
- 1
#include <bits/stdc++.h>
#include <boost/multiprecision/cpp_int.hpp>
using namespace std;
using boost::multiprecision::cpp_int;
cpp_int countMoves = 0;
void moveDisk(int n, char a, char b) {
cout << n << ' ' << a << ' ' << b << '\n';
countMoves++;
}
void tower(int n, char a, char b, char c) {
if (!n)
return;
tower(n - 1, a, c, b);
moveDisk(n, a, b);
tower(n - 1, c, b, a);
}
void target(int n, char a) {
if (!n)
return;
char dest = n % 2 ? 'B' : 'C';
if (a == dest)
target(n - 1, a);
else {
char spare = 'A' + 'B' + 'C' - a - dest;
tower(n - 1, a, spare, dest);
moveDisk(n, a, dest);
target(n - 1, spare);
}
}
int main() {
int n;
cin >> n;
if (n % 2)
cout << "ERROR\n";
else {
target(n, 'A');
cout << countMoves << '\n';
}
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。