This page is still under construction.

Parts of this page are still being built. What you see may change.

Minimum Swaps

Interview

Time limit1sMemory limit64 MB

Summary
Given permutations A and B, find the minimum number of swaps within A that turn it into B.
Level

Medium5 of 10

Topics
Array, Hash map, Graph, Sorting
Solved
No attempts yet

Problem

You are given arrays AA and BB. Each one holds the numbers 11 through NN exactly once, but the two orders may differ.

One operation swaps two numbers inside AA.

Find the minimum number of operations that makes AA equal to BB.

Input

  • The first line contains NN, the size of arrays AA and BB. (1≤N≤1,000,0001 \le N \le 1{,}000{,}000)
  • The second line contains the elements of AA, separated by single spaces.
  • The third line contains the elements of BB, separated by single spaces.

Output

Print on the first line the minimum number of operations that makes AA equal to BB.

Hint

For A=[1,4,2,3]A = [1, 4, 2, 3] and B=[4,3,1,2]B = [4, 3, 1, 2], swapping 11 with 44, then 22 with 33, then 11 with 33 turns AA into BB in three operations.

For A=[3,6,4,7,1,2,5]A = [3, 6, 4, 7, 1, 2, 5] and B=[4,3,7,6,1,5,2]B = [4, 3, 7, 6, 1, 5, 2], swapping 22 with 55, then 33 with 66, then 44 with 66, then 66 with 77 takes four operations.

Examples3

  1. Example 1

    Input
    4
    1 4 2 3
    4 3 1 2
    
    Expected output
    3
    
  2. Example 2

    Input
    7
    3 6 4 7 1 2 5
    4 3 7 6 1 5 2
    
    Expected output
    4
    
  3. Example 3

    Input
    1
    1
    1
    
    Expected output
    0