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.一进站就立刻出战
2.进站后不出站,由C的栈顶车厢出战
使用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中转站 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(); } }}
新闻热点
疑难解答