[CODE]
//====================== main.cpp =====================
#include <iostream>
#include <algorithm> //use for_each()
#include "tower.h"
using namespace std;
class X
{
public:
void operator()(int element) { cout<<element<<' '; }
};
void output(tower&, tower&, tower&);
void hnt(tower&, tower&, tower&, int);
int main()
{
int n;
while(cin>>n)
{
tower a('a',n), b('b'), c('c');
output(a, b, c);
hnt(a,b,c,n);
}
return 0;
}
void hnt(tower &source, tower &target, tower &tmp, int num)
{
static tower &p1 = source, &p2 = target, &p3 = tmp;
if(num == 1)
{
if(source.move_top_to(target) == false)
cout<<"arithmetic error"<<endl;
else
output(p1, p2, p3);
return;
}
hnt(source, tmp, target, num-1);
if(source.move_top_to(target) == false)
cout<<"arithmetic error"<<endl;
else
output(p1, p2, p3);
hnt(tmp, target, source, num-1);
}
void output(tower &t1, tower &t2, tower &t3)
{
X x;
cout<<t1.towerlabel()<<' ';
for_each(t1.begin(), t1.end(), x);
cout<<'\n';
cout<<t2.towerlabel()<<' ';
for_each(t2.begin(), t2.end(), x);
cout<<'\n';
cout<<t3.towerlabel()<<' ';
for_each(t3.begin(), t3.end(), x);
cout<<'\n';
cout<<"--------------------"<<endl;
}
//=================== tower.h ================
#ifndef TOWER_H
#define TOWER_H
#include <vector>
template class std::vector<int>;
class tower: public std::vector<int>
{
private:
const char label; //塔的标记,也许会有用
public:
tower(char ch, int m=0);
void set_plate(int); //初始化时用来设置tower中的盘子
char towerlabel() { return label; }
int top() { return this->back(); }
bool move_top_to(tower&); //从一个tower顶移动一个盘到另一个tower
};
#endif
/*可能用到的 vector<int> 的方法
iterator begin();
iterator end();
size_type size();
void clear();
void pop_back();
void push_back(int&);
*/
/===================== tower.cpp ====================
#include "tower.h"
tower::tower(char ch, int m):label(ch)
{
set_plate(m);
}
void tower::set_plate(int m)
{
clear();
for(int i=m; i>0; i--)
push_back(i);
}
bool tower::move_top_to(tower &target)
{
//移动之前检查是否违反规则
if(this == &target || this->empty())
return false;
if((!target.empty()) && (this->top() >= target.top()) )
return false;
//移动
target.push_back(this->top());
this->pop_back();
return true;
}
[/CODE]
不会界面,先编一个console程序,也许算不了什么,希望有所帮助。
给aogun看了个has a,这个改了改,改成is a了,
[QUOTE]
俺估计此事就此不了了之了
650)this.style.width=650;" align="middle" border="0">
[/QUOTE]
谢谢鼓励