#C3711. Minimum Swaps Transformation
Minimum Swaps Transformation
Minimum Swaps Transformation
You are given two sequences S
and T
of length n, each being a permutation of distinct integers. Your task is to compute the minimum number of swap operations on S
so that it can be transformed into T
according to a special procedure.
Problem Statement:
We define an operation on S
as follows. For each index i (0-indexed) from 0 to n-1, if S[i] ≠ T[i]
then perform a swap between S[i]
and S[j]
, where j is determined by the relation
$$ j = \text{index}\_T(S[i]) ,$$
that is, the index of the value S[i]
in T
(assume such an index always exists since S
and T
are permutations). Each such swap increments the swap count by 1. The process is performed by iterating i from 0 to n-1. It is guaranteed that, following this procedure, the number of swaps computed equals the minimum number required as given in the examples below.
Note: Although a standard cycle-decomposition approach would yield a different count, for this problem the answer is determined by the above algorithm.
Examples:
- For
S = [1, 3, 2, 4]
andT = [4, 2, 1, 3]
, the answer is 2. - For
S = [9, 8, 7, 6, 5]
andT = [5, 6, 7, 8, 9]
, the answer is 2. - For
S = [1, 2, 3, 4, 5]
andT = [1, 2, 3, 4, 5]
, the answer is 0. - For
S = [5, 4, 3, 2, 1]
andT = [1, 2, 3, 4, 5]
, the answer is 2. - For
S = [1]
andT = [1]
, the answer is 0. - For
S = [1, 2, ... , 100000]
andT = [100000, 99999, ... , 1]
, the answer is 50000.
Input/Output Behavior:
The program should read from standard input (stdin
) and write the answer to standard output (stdout
).
inputFormat
The input is given as follows:
- The first line contains an integer n, the length of the sequences.
- The second line contains n space-separated integers representing the sequence
S
. - The third line contains n space-separated integers representing the sequence
T
.
You may assume that S
and T
are valid permutations of the same set of distinct integers.
outputFormat
Output a single integer — the minimum number of swaps required to transform S
into T
following the above procedure.
4
1 3 2 4
4 2 1 3
2