Why Did the Cow Cross the Road 10

Given two permutations of 1..N, cyclically shift one of them and minimize the number of pairs whose order differs between the two sequences.

Medium7ArraySortingPrefix sumCombinatoricsNo attempts yetTime limit2sMemory limit512 MB

Problem

Why cows cross the road is still an open question, but it is well known that Farmer John's cows cross the road often. They cross so often that they sometimes bump into each other on the way, and John wants to fix this.

The farm has one straight road with NN pastures on each side (1N1000001 \le N \le 100\,000). Pastures for different breeds are built so differently that each pasture can hold only one specific breed: pasture ii can hold only cow breed ii. When a cow crosses the road, it moves to the pasture on the opposite side that holds its own breed.

John did not pay attention when he built the pastures, so their order is jumbled, and the paths of a cow of breed aa and a cow of breed bb may cross. Call such a pair (a,b)(a, b) a "crossing pair".

To reduce the number of crossing pairs, John came up with a way to rearrange the farm. He picks an integer kk with 0k<N0 \le k < N and moves the last kk pastures on one side of the road to the front, keeping their order. For example, if the pastures are numbered 3, 7, 1, 2, 5, 4, 6 in order and k=2k=2, then after the move they are numbered 4, 6, 3, 7, 1, 2, 5. He may apply the move to either the left side or the right side of the road, but only to one of them.

Help John make the number of crossing pairs as small as possible.

Input

The first line contains NN. Each of the next NN lines contains one pasture number, listing the pastures on the left side of the road in order. Each breed appears exactly once. The following NN lines list the pastures on the right side of the road in the same way.

Output

Print the minimum number of crossing pairs.