1 #include
2 #include
3 using namespace std;
4 //define the operation
5 class oprt
6 {
7 public:
8 int begin,end;
9 char src,dst,bri;
10 oprt(){};
11 oprt(int rbegin,int rend,char rsrc,char rdst,char rbri):
12 begin(rbegin),end(rend),src(rsrc),dst(rdst),bri(rbri){}
13 };
|
14 #define print_oprt(op) cout<<"move disk "<<(op).begin<<" from /'"<<(op).src<<"/' to /'"<<(op).dst<<"/'"< |
15 typedef stack |
16 int hanoi_s(int size,char src,char dst,char bri)
17 {
18 oprt_stack ostack;
19 oprt tmp;
20 ostack.push(oprt(1,size,src,dst,bri));
21 while (!ostack.empty())
22 {
23 tmp = ostack.top();
24 ostack.pop();
25 if (tmp.begin != tmp.end)
26 {
27 ostack.push(oprt(tmp.begin,tmp.end-1,tmp.bri,tmp.dst,tmp.src));
28 ostack.push(oprt(tmp.end,tmp.end,tmp.src,tmp.dst,tmp.bri));
29 ostack.push(oprt(tmp.begin,tmp.end-1,tmp.src,tmp.bri,tmp.dst));
30 }
31 else
32 print_oprt(tmp);
33 }
34 }
|
4 void hanoi_o(int scale,char src,char dst,char bri)
5 {
6 int cnt,srctop,dsttop,britop,last = 0;
7 stack
8 for (cnt=1 ;cnt<=scale; cnt++)
9 ssrc.push(cnt);
10
11 while (sdst.size() != scale)
12 {
13 srctop = ssrc.empty() ? 0 : ssrc.top();
14 dsttop = sdst.empty() ? 0 : sdst.top();
15 britop = sbri.empty() ? 0 : sbri.top();
16
17 if (last != srctop && ((srctop%2 && srctop>dsttop) || ((srctop%2==0) && srctop>britop)))
18 {
19 ssrc.pop();
20 last = srctop;
21 srctop % 2 ? sdst.push(srctop) : sbri.push(srctop);
22 if (srctop % 2)
23 cout<<"move disk "<
24 else
25 cout<<"move disk "<
26 }
27
28 if (last != britop && ((britop%2 && britop>srctop) || ((britop%2==0) && britop>dsttop)))
29 {
30 sbri.pop();
31 last = britop;
32 britop % 2 ? ssrc.push(britop) : sdst.push(britop);
33
34 if (britop % 2)
35 cout<<"move disk "<
36 else
37 cout<<"move disk "<
38 }
39
40 if (last != dsttop && ((dsttop%2 && dsttop>britop) || ((dsttop%2==0) && dsttop>srctop)))
41 {
42 sdst.pop();
43 last = dsttop;
44 dsttop % 2 ? sbri.push(dsttop) : ssrc.push(dsttop);
45 if (dsttop % 2)
46 cout<<"move disk "<
47 else
48 cout<<"move disk "<
49 }
50 }
51 }
|
3 #define move(disk,src,dst) cout<<"move disk "<
4 void hanoi_r(int size,char src,char dst,char bri)
5 {
6 if (size == 1)
7 move(size,src,dst);
8 else
9 {
10 hanoi_r(size-1,src,bri,dst);
11 move(size,src,dst);
12 hanoi_r(size-1,bri,dst,src);
13 }
14 }
|
#define print_oprt(op)
|
#define move(disk,src,dst)
|
Scale Stack Recursion Other (1-30)
1 0 0 0
2 0 0 0
3 0 0 0
4 0 0 0
5 0 0 0
6 0 0 0
7 0 0 0
8 0 0 0
9 0 0 0
10 0 0 0
11 0 0 0
12 0 0 0
13 0 0 0
14 0 0 0.01
15 0 0 0.01
16 0.02 0 0.01
17 0.03 0 0.03
18 0.05 0 0.05
19 0.12 0 0.12
20 0.23 0.01 0.23
21 0.49 0.01 0.47
22 0.95 0.04 0.89
23 1.92 0.07 1.87
24 3.8 0.15 3.55
25 7.65 0.3 7.52
26 15.2 0.6 14.24
27 30.49 1.2 29.7
28 61.11 2.41 57.24
29 111.15 4.29 97.56
30 201.09 7.72 184.32
|