Under construction

Still being built. Things may change

Sorting Game

Time limit1sMemory limit1024 MB

Summary
After each swap of two positions, find the minimum rounds Aizan needs to sort the permutation while Ermac delays, or -1 if Ermac can always prevent sorting.
Level

Hard8 of 10

Topics
Array, Math, Game theory
Solved
No attempts yet

Problem

Ermac and Aizan play a game with a sequence SS of length NN. Each integer from 0 to N−1N-1 appears exactly once in SS. The goal of the game is to sort the sequence in ascending order. Aizan tries to sort it, and Ermac tries to keep it unsorted for as long as possible when that cannot be avoided.

In one game, each round Ermac picks two numbers and swaps their positions, and then Aizan picks two numbers and swaps their positions. Both Ermac and Aizan may pick the same number twice so that nothing moves. If the sequence is sorted in ascending order at the end of a round, the game ends. If the sequence is already sorted at the start, the number of rounds needed is 0.

To play several games, Ermac and Aizan modify SS MM times and play a game after each change. Two arrays XX and YY of length MM are given. Games are numbered from 0 to M−1M-1 in the order they are played. Before game ii starts, the numbers at positions XiX_i and YiY_i of the sequence from the moment game i−1i-1 started are swapped, and game ii is played on the resulting sequence. The sequence at the moment game −1-1 started is defined as SS.

For each game, determine whether Aizan is guaranteed to sort the sequence after some number of rounds. If so, find the minimum number of rounds needed.

Input

The first line contains NN (1≤N≤2×1051 \le N \le 2 \times 10^5).

The second line contains the NN numbers of the sequence SS, separated by spaces.

The third line contains MM (1≤M≤6×1051 \le M \le 6 \times 10^5).

Each of the next MM lines contains XiX_i and YiY_i, separated by a space (0≤Xi,Yi<N0 \le X_i, Y_i < N).

Output

For each of the MM games, in the order the games are played, print −1-1 if the game can continue indefinitely. Otherwise, print the minimum number of rounds needed. Separate the values with spaces.

Examples2

  1. Example 1

    Input
    5
    4 3 2 1 0
    3
    0 4
    1 3
    2 2
    Expected output
    -1 0 0
  2. Example 2

    Input
    5
    4 3 2 1 0
    6
    0 1
    1 2
    2 3
    3 4
    0 1
    1 2
    Expected output
    -1 -1 -1 -1 -1 -1