Allowed Swaps

시간 제한2초메모리 제한512 MB

요약
주어진 교환 목록에 있는 위치끼리만 바꿔서 순열을 정렬하고, 불가능하면 -1을 출력한다. 교환 횟수는 500000 이하이면 된다.
난이도

보통10점 중 6점

유형
유니온 파인드, 정렬, 그래프, 구현
정답자
아직 제출이 없습니다

문제

You are given a permutation of length NN and a list of allowed swaps. Each swap is defined by two distinct integers between 1 and NN, inclusive --- positions in the permutation that can be swapped.

Your task is to sort the permutation using no more than 5⋅1055 \cdot 10^5 allowed swaps or determine that it is impossible. Note that each allowed swap can be used more than once.

입력

The first line contains a single integer NN --- the length of the permutation (3≤N≤10003 \le N \le 1000).

The second line contains NN distinct integers between 1 and NN, inclusive --- the permutation itself.

The third line contains a single integer SS (1≤S≤2⋅1051 \le S \le 2 \cdot 10^5) --- the number of allowed swaps. Then SS lines follow, each containing two integers p_ip\_i and q_iq\_i (1≤p_i,q_i≤N1 \le p\_i, q\_i \le N; p_i≠q_ip\_i \ne q\_i), denoting that elements on positions p_ip\_i and q_iq\_i can be swapped.

You may assume that no two allowed swaps coincide.

출력

If it is impossible to sort the array using no more than 5⋅1055 \cdot 10^5 swaps from the given list, print −1-1. 

Otherwise, print the number of swaps used, KK, followed by KK pairs of integers x_jx\_j and y_jy\_j (1≤x_j,y_j≤N1 \le x\_j, y\_j \le N; x_j≠y_jx\_j \ne y\_j) describing the sequence of swaps. Each pair must belong to the list of allowed swaps (formally, for each jj, there must exist ii such that either x_j=p_ix\_j = p\_i and y_j=q_iy\_j = q\_i, or x_j=q_ix\_j = q\_i and y_j=p_iy\_j = p\_i).

If there is more than one solution, print any of them. The number of swaps does not have to be minimized.

예제2

  1. 예제 1

    입력
    4
    4 1 2 3
    4
    1 2
    2 3
    3 4
    4 1
    
    예상 출력
    3
    4 1
    1 2
    2 3
    
  2. 예제 2

    입력
    4
    1 3 4 2
    2
    2 1
    2 3
    
    예상 출력
    -1