Under construction

Still being built. Things may change

Maximizer

Time limit2sMemory limit1024 MB

Summary
Given two permutations A and B of 1..N, find the minimum number of adjacent swaps in A needed to reach a permutation maximizing the sum of |a_i - b_i|.
Level

Hard8 of 10

Topics
Greedy, Combinatorics, Sorting, Math
Solved
No attempts yet

Problem

Maximizer has two permutations A=[a1,a2,⋯ ,aN]A=[a_1,a_2,\cdots,a_N] and B=[b1,b2,⋯ ,bN]B=[b_1,b_2,\cdots,b_N]. Both AA and BB have length NN and consist of distinct integers from 11 to NN.

Maximizer wants to maximize the sum of differences of each element, ∑i=1N∣ai−bi∣\sum_{i=1}^{N} |a_i - b_i|. But he can only swap two adjacent elements in AA. Precisely, he can only swap aia_i and ai+1a_{i+1} for some ii from 11 to N−1N-1. He can swap as many times as he wants.

What is the minimum number of swaps required for maximizing the difference sum?

Input

The first line contains an integer NN. (1≤N≤250 0001 \leq N \leq 250\,000)

The second line contains NN integers a1,a2,⋯ ,aNa_1,a_2,\cdots,a_N (1≤ai≤N1 \leq a_i \leq N).

The third line contains NN integers b1,b2,⋯ ,bNb_1,b_2,\cdots,b_N (1≤bi≤N1 \leq b_i \leq N).

Each of [a1,a2,⋯ ,aN][a_1,a_2,\cdots,a_N] and [b1,b2,⋯ ,bN][b_1,b_2,\cdots,b_N] is a permutation. In other words, it is consisted of distinct integers from 11 to NN.

Output

Print an integer, the minimum number of swaps required for maximizing the difference sum.

Examples2

  1. Example 1

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

    Input
    4
    3 4 1 2
    3 2 4 1
    
    Expected output
    3