Hanoi (c) time limit:MS | Memory limit:65535 KB Difficulty:3
-
Describe
-
In India, there is an old legend: in the world center of Sheng Miao (in northern India), a yellow copper plate is inserted with three stone needles. In the creation of the world, The Hindu god Brahma, on one of the needles, dressed from the bottom to the top 64 pieces of gold, the so-called Hanoi. No matter the day or night, there is always a monk in accordance with the following rules to move these gold pieces: one at a time, no matter where the needle, the small pieces must be on top of the large. The monks predicted that the world would be wiped out in a thunderbolt when all the pieces of gold were moved from the needle on which Brahma was dressed, and that the Vatican, the temples and all sentient beings would perish.
Now we have numbered three needles.
All the gold pieces at the beginning of the 1th-pin, now give you the task is to judge a series of instructions in the process, whether illegal instructions will appear.
The following two cases of illegal instruction are as follows:
1, there is no gold on a needle, but the instructions are still required from the place to move the gold plate to other needles.
2, a large piece of gold to move to a small piece of gold.
-
-
Input
-
-
The first line enters an integer N indicates the number of groups of test data (N<10)
The first line of each set of test data has two integers p,q (1<p<64,1<q<100) representing the number of layers of Hanoi and subsequent instructions
The subsequent Q line, each line is entered two integers a, a, (1<=a,b<=3) represents an instruction.
Instruction 1 2 means the top of the 1th needle to move the gold plate to the top of the 2nd needle.
Data guarantee A/b will not be the same.
-
-
Output
-
-
If there is an illegal instruction, please output illegal
Does not exist illegal directive output legal
-
-
Sample input
-
-
32 11 23 31 21 33 22 12 1
-
-
Sample output
-
-
Legalillegalillegal
The puzzle: Stack simulation on the line;
Code:
#include <cstdio> #include <cstring> #include <cmath> #include <algorithm> #include <stack >using namespace Std;const int inf=0x3f3f3f3f; #define MEM (x) memset (x,0,sizeof (x)) #define SI (x) scanf ("%d", &x) # Define SL (x) scanf ("%lld", &x) #define PI (x) printf ("%d", x) #define PL (x) printf ("%lld", x) #define P_ printf ("") # Define T_T while (t--) int main () {int t,n,q;si (T); T_t{stack<int>s[4];si (n); Si (q); for (int i=n;i>=1;i--) S[1].push (i); int a,b;bool Ans=true;while (q--) {si (a); SI (b); if (!ans) continue;if (S[a].empty ()) {ans=false;continue;} if (!s[b].empty () &&s[a].top () >s[b].top ()) {ans=false;continue;} S[b].push (S[a].top ()); S[a].pop ();} if (ans) puts ("legal"); else puts ("illegal");} return 0;}
Hanoi (c) (water, analogue)