Stack-Rail-java

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.