Under construction

Still being built. Things may change

Walk Swapping

Time limit1sMemory limit2048 MB

Summary
Given initial and final coin arrangements on a cycle, find the fewest swaps along a walk that turns one into the other, or report -1 if impossible.
Level

Hard8 of 10

Topics
Array, Prefix sum, Greedy
Solved
No attempts yet

Problem

A cycle CC with nn vertices is a graph in which vertices ii and i+1i + 1 are connected by an edge for i=1,…,n−1i = 1, \dots, n - 1, and vertices nn and 11 are connected by an edge. The vertices of CC are numbered 1 to nn.

There are nn coins, and each coin is numbered with one of {1,2,…,n}\{1, 2, \dots, n\}. Two coins may have the same number. Initially, each vertex of CC holds one coin. Two vertices can swap their coins with each other.

For a walk w=(v1,v2,…,vk)w = (v_1, v_2, \dots, v_k) in CC, a walk swapping swaps the coins on viv_i and vi+1v_{i+1} in the order i=1,2,…,k−1i = 1, 2, \dots, k - 1. A walk is a sequence of kk (≥1\geq 1) vertices in which consecutive vertices are different and adjacent in CC. You can think of a walk as the vertices visited when you traverse CC. The number kk is the length of ww. A walk of length k≥2k \geq 2 causes k−1k - 1 swaps, and a walk of length one causes no swap.

The figure below shows the walk swapping for the walk (2,1,4,1)(2, 1, 4, 1) on a cycle with 4 vertices.

For example, the walk (2,1,4,1)(2, 1, 4, 1) in the figure causes 3 swaps. The same final configuration is reached by the walk (1,2)(1, 2) with only one swap.

You are given the initial and final configurations of coins. Find a walk swapping that turns the initial configuration into the final one with the minimum total number of swaps.

Input

The first line contains an integer nn (1≤n≤3 0001 \leq n \leq 3\,000), the number of vertices in CC.

The second line contains nn integers between 1 and nn. The ii-th integer is the coin on vertex ii in the initial configuration. Values may repeat.

The third line contains nn integers between 1 and nn in the same format, giving the coin on each vertex in the final configuration.

Output

Print exactly one line containing the minimum number of swaps in a walk swapping that turns the initial configuration into the final one. If no walk swapping can do this, print -1.

Examples3

  1. Example 1

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

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

    Input
    6
    4 1 3 6 2 5
    6 2 1 3 4 5
    
    Expected output
    -1