A set of train car number 1-n
From right to left through the station
Each car can temporarily stop (stack), let the few cars on the main line and then back on the road to keep up.
Sequence number and the carriages enter the compartment wanted, it is determined whether it is possible.
The CCF materials volumes P149, Example 6.9
code show as below:
1 #include <iostream> 2 #include <string> 3 #include <cmath> 4 #include <algorithm> 5 using namespace std; 6 struct Stack 7 { 8 int a[100]; 9 int p; 10 }; 11 bool isempty(Stack *s) 12 { 13 return s->p==-1; 14 } 15 void push(Stack *s,int x) 16 { 17 s->p++; 18 s->a[s->p]=x; 19 } 20 int pop(Stack *s) 21 { 22 if(!isempty(s)) 23 { 24 return s->a[s->p--]; 25 } 26 else 27 { 28 //cout<<"The stack is empty"; 29 return -1; 30 } 31 } 32 int gettop(Stack *s) 33 { 34 if(!isempty(s)) 35 { 36 return s->a[s->p]; 37 } 38 else 39 { 40 //cout<<"The stack is empty"; 41 return -1; 42 } 43 } 44 main() 45 { 46 Stack *mystack=new Stack; 47 int a[100]={0},b[100]={0},n,*p1,*p2;//A is a sequence of interest, b is the initial sequence, b train through the station from right to left 48 BOOL In Flag = to true ; 49 mystack-> P = - . 1 ; 50 P1 = a; 51 is P2 = B; 52 is // initialization start 53 is CIN >> n-; 54 is for ( int I = 0 ; I <n-; I ++ ) 55 { 56 is B [I] = I + . 1 ; 57 is } 58 for ( int I = 0 ; I <n-; I ++ ) 59 { 60 >> CIN A [I]; 61 is } 62 is // initialization end 63 is the while (! * P1 = 0 ) 64 { 65 IF (P2 * == 0 ! && getTop (myStack) * = P1) 66 { 67 In Flag = to false ; 68 BREAK ; 69 } 70 the else 71 is { 72 IF (== * P1 * P2) 73 is { 74 P1 ++ ; 75 P2 ++; 76 } 77 else if(*p1==gettop(mystack)) 78 { 79 pop(mystack); 80 p1++; 81 } 82 else 83 { 84 push(mystack,*p2); 85 p2++; 86 } 87 } 88 } 89 if(flag) 90 { 91 cout<<"I can do it."; 92 } 93 else 94 { 95 cout<<"That is impossible."; 96 } 97 free(mystack); 98 }
end here