Magic Stone Toy
InterviewTime limit1sMemory limit256 MB
Sort a permutation of 1..N into increasing order using at most 100 reversals of adjacent segments, or report impossible.
- Level
Medium5 of 10
- Topics
- Sorting, Greedy, Implementation, Array
- Solved
- No attempts yet
Problem
Legend says the power of the kingdom of Polymath flows from magic stones. A friend who sells magic stone toys has asked you to help tidy up the shop.
The shop has toys, and their sizes are distinct natural numbers from to . You want to sort the toys by size, so that from left to right their sizes are . To do this you may perform several operations. One operation is to choose several adjacent toys and reverse their order. For example, if the sizes from left to right are and you operate on the third through fifth toys, the sizes become from left to right, and the sorting is finished.
Write a program that decides whether the toys can be sorted in at most 100 operations, and if so, finds any way to do it.
Input
The first line gives the number of toys . The second line gives integers representing the sizes of the toys, separated by spaces.
Output
If the toys cannot be sorted in at most 100 operations, print and terminate the program. If they can be sorted, print the number of operations on the first line. On each of the next lines, print the left end index and the right end index of the toys affected by that operation. For example, if you operate on the third through fifth toys from the left, print .
Constraints
If sorting is possible, the output must satisfy the following.