Sorting by moving pairs
Time limit1sMemory limit128 MB
Decide whether a permutation of 1 to N can be sorted by repeatedly relocating an adjacent pair as a block.
- Level
Medium6 of 10
- Topics
- Combinatorics, Math
- Solved
- No attempts yet
Problem
You want to sort a sequence of numbers into increasing order, and only one operation is available. Pick two neighboring numbers, lift them out as a single block without changing their order, and insert the block between any two numbers of the remaining sequence, or at the very front, or at the very back. Moving a number on its own is not allowed.
For example, 4 1 5 3 2 can be sorted like this. The pair that moves is written in italics.
4 1 5 3 2 → 3 2 4 1 5 → 3 4 1 2 5 → 1 2 3 4 5
The sequence 2 1 3, on the other hand, cannot be sorted no matter what you do.
You are given a sequence of distinct integers that uses every value from 1 to exactly once. Write a program that decides whether the sequence can be sorted using only this operation.
Input
The first line contains the number of test cases (). Each test case takes two lines. The first line contains an integer (), and the second line contains the integers of the sequence, separated by spaces. Those integers use every value from 1 to exactly once.
Output
For each test case, print YES if the sequence can be sorted and NO if it cannot, one answer per line.