Deranging Hat
InterviewTime limit2sMemory limit512 MB
Given a string, find a sorting network that turns its sorted letters back into the original string, following a specified rule.
- Level
Medium5 of 10
- Topics
- Simulation, Sorting, Greedy, Array
- Solved
- No attempts yet
Problem
A sorting network is a list of pairs of integers . Applying a pair to a string follows a single rule. If the -th character is not smaller than the -th character, swap the two characters, and otherwise leave the string as it is. The pairs of the list are applied one after another, from the first pair to the last.
An arranging hat lays out the letters it is given in ascending order. A deranging hat runs the other way. It starts from those sorted letters and puts the original word back together.
You are given a string of lowercase letters. Find a sorting network that turns the sorted letters of back into .
Input
The first line contains a string of lowercase Latin letters, 'a' to 'z'. ()
Output
Several sorting networks usually work. Only the list built by the following rule is accepted.
Let be the string with its characters sorted in ascending order. Set the string to and start with an empty list. For in this order, do the following. If , do nothing. Otherwise take the smallest with and , append the pair to the end of the list, then swap and . Such a always exists.
Print the pairs of the list in the reverse of the order in which they were appended, one pair per line, the two integers separated by a single space. Print nothing if the list is empty. The list holds at most pairs, so the output never exceeds 10000 lines, and every printed integer is between and . Applying this list to gives .