UDP Stacks
Time limit1sMemory limit1024 MB
Given a permutation, decide whether the three special stacks U, D, and P can be filled so that the elements, listed in the order they fell, come out in ascending order.
- Level
Hard8 of 10
- Topics
- Stack, Greedy, Simulation
- Solved
- No attempts yet
Problem
The UDP village has three mysterious stacks, called the U stack, the D stack, and the P stack in that order. These stacks are special: you can open and close the bottom of a stack. If you insert an element into a stack whose bottom is open, it immediately falls below the bottom. If you open the bottom of a stack whose bottom is closed, all elements stored in it fall below the bottom. In that case, the elements closer to the bottom fall first. Initially, only the bottom of the U stack is open, and the bottoms of the D stack and the P stack are closed.
One day, a permutation of length is found in the UDP village. Phoenix can use only the following two operations.
- Remove the first element of permutation and insert it into one of the three stacks. This operation is possible only when permutation is not empty.
- Close the stack whose bottom is currently open, then choose one of the stacks whose bottom is closed and open it.
Phoenix repeats the operations until permutation and all three stacks are empty. Then Phoenix lists the elements so that the ones that fell first come first. Determine whether Phoenix can rearrange these elements in ascending order.
Input
The first line contains the number of test cases .
The first line of each test case contains the length of the permutation.
The second line of each test case contains the elements of permutation , separated by spaces. Each is a distinct integer between and , inclusive.
The sum of over all test cases is guaranteed to be at most .
Output
For each test case, print YES if Phoenix can rearrange the elements in ascending order, and NO otherwise. Print one answer per line, in order.