Minimum Swaps

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

Medium5ArrayHash mapGraphSortingInterviewNo attempts yetTime limit1sMemory limit64 MB

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. (1N1,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.