问题
解法:
//这个是原版的,利用的是递归的过程
#include<iostream>
#include<fstream>
#include<stack>
#include<cstdlib>
using namespace std;
ofstream fout("C:\\data27.out");
int n;
stack<int> A,B,C;
int cnt=0;
void print()
{
cout<<"A:\t"<<A.size()<<endl;;
while(!A.empty())
{
cout<<A.top()<<"\t";
A.pop();
}
cout<<endl;
cout<<"B:\t"<<B.size()<<endl;
while(!B.empty())
{
cout<<B.top()<<"\t";
B.pop();
}
cout<<endl;
cout<<"C:\t"<<C.size()<<endl;
while(!C.empty())
{
cout<<C.top()<<"\t";
C.pop();
}
cout<<endl;
}
void HanNuoTa(stack<int>& A,stack<int>& B,stack<int>& C,int n)
{
if(n==1)
{
B.push(A.top());
A.pop();
return;
}
//这两步多此一举了,可以合并
HanNuoTa(A,B,C,n-1);
HanNuoTa(B,C,A,n-1);
B.push(A.top());
A.pop();
HanNuoTa(C,B,A,n-1);
}
int main()
{
cin>>n;
for(int i=n;i>0;--i)
A.push(i);
HanNuoTa(A,B,C,n);
print();
system("pause");
return 0;
}
//这是算法书上的
#include<iostream>
#include<stack>
#include<cstdlib>
using namespace std;
int n;
stack<int> A,B,C;
int cnt=0;
void print()
{
cout<<"A:\t"<<A.size()<<endl;;
while(!A.empty())
{
cout<<A.top()<<"\t";
A.pop();
}
cout<<endl;
cout<<"B:\t"<<B.size()<<endl;
while(!B.empty())
{
cout<<B.top()<<"\t";
B.pop();
}
cout<<endl;
cout<<"C:\t"<<C.size()<<endl;
while(!C.empty())
{
cout<<C.top()<<"\t";
C.pop();
}
cout<<endl;
}
void HanNuoTa(stack<int>& A,stack<int>& B,stack<int>& C,int n)
{
if(n==1)
{
C.push(A.top());
A.pop();
}
else
{
//唯一的区别在在这里,递归过程减半
HanNuoTa(A,C,B,n-1);
C.push(A.top());
A.pop();
HanNuoTa(B,A,C,n-1);
}
}
int main()
{
cin>>n;
for(int i=n;i>0;--i)
A.push(i);
HanNuoTa(A,B,C,n);
print();
system("pause");
return 0;
}