Railway Station
Time limit10sMemory limit512 MB
Decide for each target permutation whether coaches arriving as 1..N can leave a single dead-end siding in that order.
- Level
Medium4 of 10
- Topics
- Stack, Simulation
- Solved
- No attempts yet
Problem
There is a famous railway station in a hilly country. The station was built many decades ago, when funds were extremely limited, so only a single surface track could be laid. Moreover, the station could only be a dead-end one (see the picture), and for lack of space it has only one track.

The local tradition is that every train arriving from direction continues in direction with its coaches reorganized in some way. The train arriving from direction has coaches (), numbered in the order they arrive. The chief of train reorganization must know whether the coaches leaving in direction can be marshaled into the order .
Help him by writing a program that decides whether the required order of coaches can be obtained. You may assume that single coaches can be disconnected from the train before they enter the station and that they can move by themselves until they are on the track in direction . You may also assume that at any time the station can hold as many coaches as necessary. However, once a coach has entered the station, it cannot return to the track in direction , and once it has left the station in direction , it cannot return to the station.
Input
The input consists of blocks of lines. Each block except the last describes one train and one or more requirements for its reorganization.
The first line of a block contains the integer described above. Each of the following lines of the block contains a permutation of . The last line of the block contains just .
The last block consists of a single line containing .
Output
For each input line that holds a permutation, print one line, in input order. The line contains Yes if the coaches can be marshaled in the order required on that input line, and No otherwise.
After the lines for one input block, print one empty line. Print nothing for the last block of the input (the block that is a single 0).