Hanoi(栈实现)

 1 #include <iostream>
 2 #include <stack>
 3 using namespace std;
 4 stack<int> S[3];
 5 int ans;
 6 void move(int x,int y){
 7      int temp=S[x].top();
 8     S[x].pop();
 9     S[y].push(temp);
10     cout<<x<<" --> "<<y<<endl;
11     ans++;
12 }
13 void hanoi(int A,int B,int C,int n){
14     if(n==1){
15         move(A,C);
16         return;
17     }
18     hanoi(A,C,B,n-1);
19     move(A,C);
20     hanoi(B,A,C,n-1);
21 }
22 int main() {
23     int n;
24     cin>>n;
25     for(int i=n;i>=1;i--){
26         S[0].push(i);
27     }
28     hanoi(0,1,2,n);
29     while(!S[2].empty()){
30         S[2].pop();
31     }
32     cout<<"¹²"<<ans<<"´Î";
33     return 0;
34 }
原文地址:https://www.cnblogs.com/zuiaimiusi/p/10843072.html