算法2,按规律从上面挪,最小的一个不用判断是不是有比它还小的。
感觉递归象列方程。
直接操作栈象四则运算,一锅粥。
[CODE]#include <iostream>
#include "tower.h"
using namespace std;
void output(tower&, tower&, tower&);
void hnt(tower&, tower&, tower&, int);
int main()
{
int n;
while(cin>>n)
{
tower source('a',n), tmp('b'), dest('c');
output(source, tmp, dest);
hnt(source,tmp,dest,n);
}
system("pause");
return 0;
}
void hnt(tower &source, tower &tmp, tower &dest, int high)
{
// destination select , p[0] source
tower *p[3] = { &source,
(high%2 == 0 ? &tmp : &dest),
(high%2 == 0 ? &dest : &tmp) };
int i=0, prev=2, next=1; // index
while(1)
{
p[i]->move_top_to( *p[next] ); //move 1 from current to next tower
output(source, tmp, dest);
if(dest.size() == high)
break; // finish
i = (i+1)%3; // index + 1
prev = (prev+1)%3;
next = (next+1)%3;
if( p[prev]->size() == 0 )
p[next]->move_top_to( *p[prev] );
else if( p[next]->size() == 0 )
p[prev]->move_top_to( *p[next] );
else if( p[prev]->top() > p[next]->top() )
p[next]->move_top_to( *p[prev] );
else // if( p[a]->top() < p[b]->top )
p[prev]->move_top_to( *p[next] );
output(source, tmp, dest);
}
}
void output(tower &t1, tower &t2, tower &t3)
{
for(int i=0; i<t1.size(); i++)
cout<<t1[i]<<' ';
cout<<'\n';
for(int i=0; i<t2.size(); i++)
cout<<t2[i]<<' ';
cout<<'\n';
for(int i=0; i<t3.size(); i++)
cout<<t3[i]<<' ';
cout<<"\n--------------------"<<endl;
}
[/CODE]