Problem Description: There is a railway station in a city. The rails are laid. There are n carriages entering the station from a direction, numbered 1~n in the order of pit stops. Your task is to have them enter the B-direction rails in a certain order and exit the station. In order to reorganize the car, you can use the Transfer Station C, for each car, once entered C can no longer enter a, once C enters B can not go back to C.
Test data
Input Sample:
5
5 4 3) 2 1
6
6 5 4 3 2 1
5
5 4 1) 2 3
Sample output:
Yes
Yes
No
ImportJava.util.Scanner;ImportJava.util.Stack;/*** Rail *@authorNEU-2015 **/ Public classDemo { Public Static voidMain (string[] args) {Scanner input=NewScanner (system.in); intx; int[] array; Stack<Integer> stack =NewStack<integer>(); BooleanFlag; intA; intb; while(Input.hasnext ()) {flag=true; b= 1; A= 1; X=Input.nextint (); Array=New int[x]; for(inti = 0; i < x; i++) {Array[i]=Input.nextint (); } //Key Parts while(A <=x) {if(Array[a-1] = = b) {//1. The incoming team is equal to the teama++; b++; } Else if(!stack.empty () && stack.peek () = = Array[a-1]) {//2. The team is not equal to the team, but the top elements of the middle stack are equal to the team elements.Stack.pop (); A++; } Else if(b <= x) {//3. The team is not equal to the team top and out of the team will be in the team element pressure stackStack.push (b++); } Else{//4. The result end loop in the input is not possibleFlag =false; Break; } } if(!flag) {System.out.println ("No"); } Else{System.out.println ("Yes"); } } }}
Stack-Rail-java