Sorting with allowed swaps

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 MB

Problem

You are given a permutation of the numbers 1 to NN, where every number appears once.

You are also given QQ pairs of positions (a,b)(a, b). Each pair means you may swap the number at position aa with the number at position bb, 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 NN (1N10001 \le N \le 1000).

The second line has NN distinct integers between 1 and NN, the permutation itself.

The third line has the number of allowed swaps QQ (1Q2000001 \le Q \le 200000).

Each of the next QQ lines has two positions aa and bb that may be swapped. Both are between 1 and NN, 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.

  1. Build a graph whose vertices are the positions 1 to NN 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 FF, otherwise drop it. FF then holds a spanning tree of every connected component.
  2. Let SS be the set of remaining positions, starting at {1,2,,N}\{1, 2, \dots, N\}. Repeat the following until SS is empty.
    1. Among the vertices of SS that have at most one neighbor of SS in FF, let uu be the one with the smallest number. Such a vertex always exists.
    2. If position uu does not hold the value uu, let pp be the position that holds the value uu. Inside FF restricted to SS, the path between pp and uu is unique. Walk that path from pp toward uu, swap the values of each neighboring pair of positions on the path in turn, and print those two positions for every swap.
    3. Remove uu from SS.
  3. 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 N(N1)/2N(N-1)/2 swaps, so the number of swaps never exceeds 500000.