67 lines
1.4 KiB
C++
67 lines
1.4 KiB
C++
|
/**
|
|||
|
* File: hanota.cpp
|
|||
|
* Created Time: 2023-07-17
|
|||
|
* Author: krahets (krahets@163.com)
|
|||
|
*/
|
|||
|
|
|||
|
#include "../utils/common.hpp"
|
|||
|
|
|||
|
/* <20>ƶ<EFBFBD>һ<EFBFBD><D2BB>Բ<EFBFBD><D4B2> */
|
|||
|
void move(vector<int> &src, vector<int> &tar) {
|
|||
|
// <20><> src <20><><EFBFBD><EFBFBD><EFBFBD>ó<EFBFBD>һ<EFBFBD><D2BB>Բ<EFBFBD><D4B2>
|
|||
|
int pan = src.back();
|
|||
|
src.pop_back();
|
|||
|
// <20><>Բ<EFBFBD>̷<EFBFBD><CCB7><EFBFBD> tar <20><><EFBFBD><EFBFBD>
|
|||
|
tar.push_back(pan);
|
|||
|
}
|
|||
|
|
|||
|
/* <20><><EFBFBD>⺺ŵ<E2BABA><C5B5><EFBFBD><EFBFBD><EFBFBD><EFBFBD> f(i) */
|
|||
|
void dfs(int i, vector<int> &src, vector<int> &buf, vector<int> &tar) {
|
|||
|
// <20><> src ֻʣ<D6BB><CAA3>һ<EFBFBD><D2BB>Բ<EFBFBD>̣<EFBFBD><CCA3><EFBFBD>ֱ<EFBFBD>ӽ<EFBFBD><D3BD><EFBFBD><EFBFBD>Ƶ<EFBFBD> tar
|
|||
|
if (i == 1) {
|
|||
|
move(src, tar);
|
|||
|
return;
|
|||
|
}
|
|||
|
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> f(i-1) <20><><EFBFBD><EFBFBD> src <20><><EFBFBD><EFBFBD> i-1 <20><>Բ<EFBFBD>̽<EFBFBD><CCBD><EFBFBD> tar <20>Ƶ<EFBFBD> buf
|
|||
|
dfs(i - 1, src, tar, buf);
|
|||
|
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> f(1) <20><><EFBFBD><EFBFBD> src ʣ<><CAA3>һ<EFBFBD><D2BB>Բ<EFBFBD><D4B2><EFBFBD>Ƶ<EFBFBD> tar
|
|||
|
move(src, tar);
|
|||
|
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> f(i-1) <20><><EFBFBD><EFBFBD> buf <20><><EFBFBD><EFBFBD> i-1 <20><>Բ<EFBFBD>̽<EFBFBD><CCBD><EFBFBD> src <20>Ƶ<EFBFBD> tar
|
|||
|
dfs(i - 1, buf, src, tar);
|
|||
|
}
|
|||
|
|
|||
|
/* <20><><EFBFBD>⺺ŵ<E2BABA><C5B5><EFBFBD><EFBFBD><EFBFBD><EFBFBD> */
|
|||
|
void solveHanota(vector<int> &A, vector<int> &B, vector<int> &C) {
|
|||
|
int n = A.size();
|
|||
|
// <20><> A <20><><EFBFBD><EFBFBD> n <20><>Բ<EFBFBD>̽<EFBFBD><CCBD><EFBFBD> B <20>Ƶ<EFBFBD> C
|
|||
|
dfs(n, A, B, C);
|
|||
|
}
|
|||
|
|
|||
|
/* Driver Code */
|
|||
|
int main() {
|
|||
|
// <20>б<EFBFBD>β<EFBFBD><CEB2><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ӷ<EFBFBD><D3B6><EFBFBD>
|
|||
|
vector<int> A = {5, 4, 3, 2, 1};
|
|||
|
vector<int> B = {};
|
|||
|
vector<int> C = {};
|
|||
|
|
|||
|
cout << "<EFBFBD><EFBFBD>ʼ״̬<EFBFBD>£<EFBFBD>\n";
|
|||
|
cout << "A =";
|
|||
|
printVector(A);
|
|||
|
cout << "B =";
|
|||
|
printVector(B);
|
|||
|
cout << "C =";
|
|||
|
printVector(C);
|
|||
|
|
|||
|
solveHanota(A, B, C);
|
|||
|
|
|||
|
cout << "Բ<EFBFBD><EFBFBD><EFBFBD>ƶ<EFBFBD><EFBFBD><EFBFBD><EFBFBD>ɺ<EFBFBD><EFBFBD><EFBFBD>\n";
|
|||
|
cout << "A =";
|
|||
|
printVector(A);
|
|||
|
cout << "B =";
|
|||
|
printVector(B);
|
|||
|
cout << "C =";
|
|||
|
printVector(C);
|
|||
|
|
|||
|
return 0;
|
|||
|
}
|