PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#FT0000156. Bò qua đường – Số giao nhau ít nhất (Why Did the Cow Cross the Road (Minimum Crossings))

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Bò qua đường – Số giao nhau ít nhất (Why Did the Cow Cross the Road (Minimum Crossings))

Why Did the Cow Cross the Road (Minimum Crossings)

Source: USACO

Version: Phuoc Hung OJ Extended

Problem Statement

Two sides of a road each contain exactly one field for every breed 1,2,…,n1,2,\ldots,n, in the permutation orders AA and BB. Connect the fields of the same breed across the road. Two connections cross if their relative order is reversed between the sides. You may apply any cyclic shift to exactly one side (including no shift); arbitrary rearrangements or simultaneous shifts of both sides are not allowed. Find the minimum number of crossing pairs. Either side may yield the optimum.

Input

The first line contains nn. The next nn integers form permutation AA; the following nn integers form permutation BB. The original USACO format puts each integer on its own line.

Output

Print a 64-bit integer: the minimum number of crossing pairs.

Subtasks

  • Subtask 1 (20 points): 1≤n≤101\le n\le 10; Both sequences AA and BB are permutations of 1,2,…,n1,2,\ldots,n.
  • Subtask 2 (30 points): 1≤n≤30001\le n\le 3000; Both sequences AA and BB are permutations of 1,2,…,n1,2,\ldots,n.
  • Subtask 3 (50 points): 1≤n≤1000001\le n\le 100000; Both sequences AA and BB are permutations of 1,2,…,n1,2,\ldots,n.

Examples

Example 1

Input

5
5
4
1
3
2
1
3
2
5
4

Output

0

Explanation

Side AA is 5,4,1,3,25,4,1,3,2 and side BB is 1,3,2,5,41,3,2,5,4. Rotating AA left by two positions produces 1,3,2,5,41,3,2,5,4, exactly matching BB, so no connections cross and the optimum is 0.

Example 2

Input

3
1
2
3
3
2
1

Output

1

Explanation

Initially all three pairs are inverted. A one-position rotation yields orders 2,3,12,3,1 and 3,2,13,2,1, with exactly one inversion. No rotation can make the count zero.