#C2643. Minimum Swaps to Transform Array

    ID: 45982 Type: Default 1000ms 256MiB

Minimum Swaps to Transform Array

Minimum Swaps to Transform Array

You are given two arrays: nums and target. The array nums is a non-empty array of distinct integers, and target is a permutation of nums (i.e. target is obtained by shuffling nums). Your task is to determine the minimum number of swap operations required to transform nums into target. Each swap operation exchanges the positions of two elements in the array. The answer should output the total number of swaps performed, along with a list of the swaps where each swap is represented by the 0-indexed positions of the two elements being swapped.

The approach can be understood as follows: when nums[i] ≠ target[i], find the index j such that nums[j] = target[i] and swap the two elements. Repeat this process until nums matches target completely. Mathematically, if you denote the initial array as \(A = [a_0, a_1, \dots, a_{n-1}]\) and target as \(B = [b_0, b_1, \dots, b_{n-1}]\), then for each index \(i\) where \(a_i \neq b_i\), there exists an index \(j\) such that \(a_j = b_i\). Swapping these minimizes the number of discrepancies.

inputFormat

The input is read from stdin and has the following format:

T
n
nums[0] nums[1] ... nums[n-1]
target[0] target[1] ... target[n-1]
... (repeated for T test cases)

Where:

  • T is the number of test cases.
  • For each test case, n is the number of elements in the arrays nums and target.
  • The next n integers represent the array nums.
  • The following n integers represent the array target.

outputFormat

For each test case, print the result to stdout with the following format:

m
i1 j1
i2 j2
... (m swaps total)

Where:

  • m is the number of swap operations performed.
  • Each subsequent line represents a swap between the indices i and j.
## sample
1
3
1 3 2
3 2 1
2

0 1 1 2

</p>