It's kinda hard, I still read.
Hanoi is mainly the procedure needs to think about, think is very simple
Hanoi |
Difficulty level: B; run time limit: 1000ms; operating space limit: 256000KB; code length limit: 2000000B |
Question Description |
The classic Hanoi game believes that many students will play, the rules do not have to repeat, the encyclopedia is OK. There are three pillars a,b,c,a pillars with n sizes of plates, any two plates, the upper plate must be smaller than the plate below. Now, please write your program to calculate how to move the n plates to the C pillar, move only one plate at a time, move through the B pillars, any state, the plates of each pillar must be placed on a large plate on a small plate. Now enter two positive integers n and m, indicating that there are n plates, please output the Move method of step m. |
Input |
Two positive integers n and M |
Output |
Move method of step m |
Input example |
3 4 |
Output example |
A-->c |
Other Notes |
Data range: 0<n<16,0<m<2^n. Sample Description: When n=3, the first step a-->c, the second step a-->b, the third step c-->b, the fourth step a-->c, fifth step b-->a, sixth step b-->c, seventh step a-->c, the subject should output fourth step a-- >c. |
#include <iostream>using namespacestd;voidWriteintX//output Function{ if(x==0) {Putchar ('0'); return ; } if(x<0) {Putchar ('-'); X=-x; } intlen=0, buf[ the]; while(x) {Buf[len++]=x%Ten; X/=Ten; } for(inti=len-1; i>=0; i--) Putchar (buf[i]+'0'); return ;}intRead ()//Input Function{ intx=0, f=1;CharCh=GetChar (); while(ch<'0'|| Ch>'9') { if(ch=='-') f=-1; CH=GetChar (); } while(ch>='0'&&ch<='9') {x=x*Ten+ch-'0'; CH=GetChar (); } returnx*F;}intn,m,nthstep=0;//N is the number of plates, M is the first step, Nthstep said now is the first stepvoidMoveintNCharACharCCharb//The move function acts as a transition column for the B-column, moving the N-piece on the A-column to the C-pillar{ if(n==0)return;//if the plate has been removed, the procedure is finished.Move (n1, a,b,c);//first move the A-column forward n-1 plate to the B-pillar, the C-pillar as a transition columnnthstep++; if(nthstep==m)//reached the output of step m, end the program{cout<<a<<" -"<<C; Exit (0); } Move (n-1, b,c,a);//The column A is used as a transition column, and the n-1 plate on the B-pillar is moved to the C-pillar . return;//End}intMain () {n=read (); M=read (); Move (N,'A','C','B');//The B-pillar acts as a transition column, moving n pieces on the A column to the C-pillar return 0;}
Hanoi Tower Problem