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.
Medium7GraphDFSUnion-findSimulationNo attempts yetTime limit0.5sMemory limit128 MBYou are given a permutation of the numbers 1 to N, where every number appears once.
You are also given Q pairs of positions (a,b). Each pair means you may swap the number at position a with the number at position b, 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.
The first line has the length of the permutation N (1≤N≤1000).
The second line has N distinct integers between 1 and N, the permutation itself.
The third line has the number of allowed swaps Q (1≤Q≤200000).
Each of the next Q lines has two positions a and b that may be swapped. Both are between 1 and N, and they differ. The same pair can appear several times, and the two positions can come in either order.
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.
The rule uses at most N(N−1)/2 swaps, so the number of swaps never exceeds 500000.