Problem:
Bozosort

　

Bozosort, as well as Bogosort, is a very inefficient sort algorithm. It is a random number-based algorithm that sorts sequence elements following the steps as below:

Randomly select two elements and swap them.

Verify if all the elements are sorted in increasing order.

Finish if sorted, else return to 1.

To analyze Bozosort, you have decided to simulate the process using several predetermined pairs of elements.

You are given several commands to swap two elements. Make a program to evaluate how many times you have to run the command before the sequence is aligned in increasing order.

Input

The input is given in the following format.

$N$
$a_1$ $a_2$ ... $a_N$
$Q$
$x_1$ $y_1$
$x_2$ $y_2$
$...$
$x_Q$ $y_Q$

The first line provides the number of sequence elements $N$ ($2 \leq N \leq 300,000$). The second line provides an array of integers $a_i$ ($1 \leq a_i \leq 10^9$) that constitutes the sequence. Each of the subsequent $Q$ lines provides a pair of integers $x_i,y_i$ ($1 \leq x_i,y_i \leq N$) that represent the $i$-th command, which swaps the two elements indicated by $x_i$ and $y_i$ ($x_i \ne y_i$).

Output

If neat alignment in increasing order is realized the first time after execution of multiple commands, output at what time it was. Output 0 if the initial sequence is aligned in increasing order, and -1 if exhaustive execution still failed to attain the goal.

Sample Input 1

6
9 7 5 6 3 1
3
1 6
2 5
3 4

Sample Output 1

2

Sample Input 2

4
4 3 2 1
2
1 2
3 4

Sample Output 2

-1

Sample Input 3

5
1 1 1 2 2
1
1 2

Sample Input 3

0

Solution in JAVA (judge verdict: Accepted)

import java.util.*;
class Main{
    static final int INF = 2000000000;
    int N, diff;
    int[] A;
    Scanner sc;

    void update(int i, int v){
        int d1 = 0, d2 = 0;
        if ( A[i-1] > A[i] ) d1++;
        if ( A[i] > A[i+1] ) d1++;
        A[i] = v;
        if ( A[i-1] > A[i] ) d2++;
        if ( A[i] > A[i+1] ) d2++;
        diff += (d2 - d1);
    }

    void activate(){
        sc = new Scanner(System.in);
        N = sc.nextInt();
        A = new int[N+2];
        for ( int i = 1; i <= N; i++ ) A[i] = sc.nextInt();
        A[0] = -INF;
        A[N+1] = INF;
        System.out.println(solve());
    }
    
    
    int solve(){
        int a, b, q, v1, v2;
        diff = 0;
        for ( int i = 1; i <= N; i++ ) {
            if ( A[i-1] > A[i] ) diff++;
        }
        if ( diff == 0 ) return 0;
        q = sc.nextInt();
        for ( int i = 1; i <= q; i++ ){
            a = sc.nextInt();
            b = sc.nextInt();
            v1 = A[a];
            v2 = A[b];
            update(a, v2);
            update(b, v1);
            if ( diff == 0 ) return i;
        }

        return -1;
    }

    public static void main(String[] args){ new Main().activate(); }
}