Title Link: http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=1953
All must know the puzzle named "The Towers of Hanoi". The puzzle has three pegs (peg 1, Peg 2 and Peg 3) and N disks of different radii. Initially all disks is located on the first peg, ordered by their radii-the largest in the bottom, the smallest at the Top. In each turn of the topmost disc from any peg and move it to another peg, the only rule says so may not pl Ace the disc atop any smaller disk. The problem is to move all disks to the last Peg (Peg 3). I Use the different integersa(1 <=a<= 3) andb(1 <=b<= 3) to indicate a move. It means to move the topmost disk of pegaTo the top of pegb. A move is valid if and only if there are at least one disk on pegaAnd the topmost disk of pegaCan is moved on the pegbWithout breaking the former rule.
Give some moves of a game, can you Give out the result of the game?
Input
Standard input would contain multiple test cases. The first line of the input was a single integer t (1 <= T <=) which is the number of the test cases . And it'll be followed byT consecutive test cases.
The first line of all test case was a single line containing 2 integers n (1 <= n <=) and m (1 <= m <= 12000) which is the number of disks and the number of the moves. Then m lines of moves follow.
Output
For each test case, output an integer in a single line according to the result of the moves.
Note:
(1) If There is a invalid move before all disks being on peg 3 and the invalid move was the p-th move of this CAs E (start from 1), output the integer- p and the moves after this move (if any) is ignored.
(2) If after the p-th Move all disks is on peg 3 without any invalid move, output the integer p And the moves after this move (if any) is ignored.
(3) Otherwise output the integer 0 please.
Sample Input
32 31 21 32 32 31 21 33 22 31 31 23 2
Sample Output
3-30
Author:CAO, Peng
Source:Zhejiang University Local Contest
The code is as follows:
#include <cstdio> #include <stack> #include <iostream>using namespace Std;stack<int>s[4];int Ans,flog,p,n,m,t,step,k,i;int x, Y,a,b, f;void judge (int a, int b), int main () {while (~SCANF ("%d", &t)) { while (t--) {scanf ("%d%d", &n,&m); flog = ans = p = k = Step = 0; for (i = 0; i < 4; i++) {while (!s[i].empty ()) S[i].pop (); } for (i = n; I >= 1; i--) S[1].push (i); for (i = 1; I <= m; i++) {scanf ("%d%d", &a,&b); if (flog) continue; ans++; if (s[a].empty () = = 1) {flog = 1; Step = ans; Continue } judge (A, B); if (S[3].size () ==n) {flog = 2;Step = ans; }} if (flog = = 1) printf ("-%d\n", step); else if (s[3].size () = = N) printf ("%d\n", step); else printf ("0\n"); }} return 0;} void judge (int a, int b) {x = S[a].top (); if (s[b].empty () = = 1) {S[b].push (x); S[a].pop (); Return } Else y = S[b].top (); if (x > y) {flog = 1; Step = ans; Return } else {S[b].push (x); S[a].pop (); }}
ZOJ 2954 Hanoi Tower (analog AH)