KTX
Time limit1sMemory limit128 MB
Decide whether a departure permutation can be reordered into ascending grade order using a direct main line and two LIFO bypass tracks.
- Level
Medium6 of 10
- Topics
- Stack, Backtracking, Simulation
- Solved
- No attempts yet
Problem
Korail is starting a pilot service that gives every KTX train on the Seoul to Busan line a grade. The grades are through , and a train with a smaller number has to reach the destination station earlier.
The track has one main line and two bypass tracks, as in the picture.

Trains reach the junction in the order they left the departure station. At the junction each train takes one of these two options.
- It stays on the main line. Trains on the main line cannot stop or overtake, so they enter the destination station in the order they passed the junction.
- It pulls into one of the two bypass tracks and waits. A train on a bypass track can run as slowly as it likes, so it can come out as late as you want, but it rejoins the main line only after every train that entered the same bypass track later has left. A bypass track holds any number of trains.
For example, if the departure order is , send grade 1 down the main line, park grade 3 on a bypass track, let grade 2 pass, then release grade 3, and finally send grade 4 through. The trains enter the destination station in the order .
Given the departure order, write a program that decides whether the trains can enter the destination station in grade order, from 1 to .
Input
Input comes from standard input. The first line has the number of test cases (). Each test case is two lines. The first line has the number of trains (), and the second line has the grades in departure order, separated by single spaces. Every is between and and they are all different, so each number from to appears exactly once.
Output
Output goes to standard output. Print one line per test case: YES if the trains can arrive in grade order, NO otherwise.