棧-鐵軌-Java

來源:互聯網
上載者:User

標籤:測試資料   http   public      ==   div   火車站   nbsp   author   

問題描述:某城市有一個火車站。鐵軌鋪設。有N節車廂從A方向駛入車站,按進站順序編號為1~n。你的任務是讓他們按照某種特定的順序進入B方向的鐵軌並駛出車站。為了重組車廂,可以藉助中轉站C,對於每個車,一旦進入c就不能再進入A,一旦c進入B就不能回到c。

測試資料

   輸入範例:

    5
    5 4 3 2 1

    6
    6 5 4 3 2 1

    5
    5 4 1 2 3

  輸出範例:

    Yes

    Yes

    No

 

import java.util.Scanner;import java.util.Stack;/** * 鐵軌 * @author NEU-2015 * */public class Demo {    public static void main(String[] args) {        Scanner input = new Scanner(System.in);        int x;        int[] array;        Stack<Integer> stack = new Stack<Integer>();        boolean flag;        int a;         int b;        while(input.hasNext()) {            flag = true;            b = 1;            a = 1;            x = input.nextInt();            array = new int[x];            for(int i = 0; i < x; i++) {                array[i] = input.nextInt();            }                                    //關鍵區段            while(a <= x) {                if(array[a-1] == b) {     //1.進隊 與 出隊 相等                    a++;                    b++;                } else if(!stack.empty() && stack.peek() == array[a-1]) { //2.進隊 與 出隊 不相等 但是 中間棧頂元素 與 出隊 元素相等                    stack.pop();                    a++;                } else if(b <= x) {  //3.進隊 與 出隊不相等 棧頂 與 出隊 不相等 將進隊元素壓棧                    stack.push(b++);                } else {             //4.不可能出現輸入中 的結果  結束迴圈                    flag = false;                    break;                }            }                                                if(!flag) {                System.out.println("No");            } else {                System.out.println("Yes");            }        }    }}

 

棧-鐵軌-Java

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.