Sorting with allowed swaps
Time limit0.5sMemory limit128 MB
Given a permutation and allowed swaps, decide if the given pairs can sort it and output the swaps produced by the described leaf-removal rule on the spanning forest.
- Level
Medium7 of 10
- Topics
- Graph, DFS, Union-find, Simulation
- Solved
- No attempts yet
Problem
You are given a permutation of the numbers 1 to , where every number appears once.
You are also given pairs of positions . Each pair means you may swap the number at position with the number at position , and you may use the same pair many times.
Decide whether the allowed swaps can sort the permutation into increasing order. If they can, print the swap sequence defined by the rule in the output section. You may not use more than 500000 swaps.
Input
The first line has the length of the permutation ().
The second line has distinct integers between 1 and , the permutation itself.
The third line has the number of allowed swaps ().
Each of the next lines has two positions and that may be swapped. Both are between 1 and , and they differ. The same pair can appear several times, and the two positions can come in either order.
Output
If the allowed swaps cannot sort the permutation, print NEMOGUCE on the first line.
Otherwise print the swaps that the following rule produces, one per line, in the order the rule produces them. A permutation can usually be sorted in many ways, so only the sequence this rule produces is accepted.
- Build a graph whose vertices are the positions 1 to and whose edges are the given pairs. Scan the edges in input order. If the two endpoints are not connected yet, add the edge to a forest , otherwise drop it. then holds a spanning tree of every connected component.
- Let be the set of remaining positions, starting at . Repeat the following until is empty.
- Among the vertices of that have at most one neighbor of in , let be the one with the smallest number. Such a vertex always exists.
- If position does not hold the value , let be the position that holds the value . Inside restricted to , the path between and is unique. Walk that path from toward , swap the values of each neighboring pair of positions on the path in turn, and print those two positions for every swap.
- Remove from .
- Print one swap per line, writing the two swapped positions in increasing order, separated by one space. If no swap is needed, print nothing.
The rule uses at most swaps, so the number of swaps never exceeds 500000.