https://vjudge.net/PRoblem/UVA-514
There is a famous railway station in PopPush City. Country there is incredibly hilly. The station was built in last century. Unfortunately, funds were extremely limited that time. It was possible to establish only a surface track. Moreover, it turned out that the station could be only a dead-end one (see picture) and due to lack of available space it could have only one track.

The local tradition is that every train arriving from the direction A continues in the direction B with coaches reorganized in some way. Assume that the train arriving from the direction A has
coaches numbered in increasing order
. The chief for train reorganizations must know whether it is possible to marshal coaches continuing in the direction B so that their order will be
. Help him and write a program that decides whether it is possible to get the required order of coaches. You can assume that single coaches can be disconnected from the train before they enter the station and that they can move themselves until they are on the track in the direction B. You can also suppose that at any time there can be located as many coaches as necessary in the station. But once a coach has entered the station it cannot return to the track in the direction A and also once it has left the station in the direction B it cannot return back to the station.

The last line of the block contains just 0.
The last block consists of just one line containing 0.
. In addition, there is one empty line after the lines corresponding to one block of the input file. There is no line in the output file corresponding to the last ``null'' block of the input file.
YesNoYes火車進出站只有兩種情況
1.一進站就立刻出戰(zhàn)
2.進站后不出站,由C的棧頂車廂出戰(zhàn)
使用A表示進站口,B表示出站口,s堆棧表示C站,然后模擬列車進出站運動
import java.util.Scanner;import java.util.Stack;public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); while(true){ int n = scan.nextInt(); if(n==0) break; while(true){ int[] target = new int[n+1]; int m = scan.nextInt(); if(m==0) break; target[1] = m; for(int i=2;i<=n;i++){ target[i] = scan.nextInt(); } int A = 1,B = 1;//A是進站口,B出站口 boolean ok = true; Stack<Integer> s = new Stack<Integer>();//模擬C中轉(zhuǎn)站 while(B<=n){ if(A==target[B]){//表示從A進站后就立刻出站 A++; B++; }else if(!s.isEmpty()&&s.peek()==target[B]){//表示C中第一個車廂出站 s.pop(); B++; }else if(A<=n){//表示從A站進站 s.push(A++); }else{ ok = false; break; } } System.out.println(ok?"Yes":"No"); } System.out.println(); } }}
新聞熱點
疑難解答