Sasha and Dima want to buy two $n$-tier cakes. Each cake should consist of $n$ different tiers: from the size of $1$ to the size of $n$. Tiers should go in order from the smallest to the biggest (from top to bottom).

They live on the same street, there are $2 \cdot n$ houses in a row from left to right. Each house has a pastry shop where you can buy a cake tier. Unfortunately, in each pastry shop you can buy only one tier of only one specific size: in the $i$-th house you can buy a tier of the size $a_i$ ($1 \le a_i \le n$).

Since the guys carry already purchased tiers, and it is impossible to insert a new tier in the middle of the cake, they agreed to buy tiers from the smallest to the biggest. That is, each of them buys tiers in order: $1$, then $2$, then $3$ and so on up to $n$.

Initially, Sasha and Dima are located near the first (leftmost) house. Output the minimum distance that they will have to walk in total to buy both cakes. The distance between any two neighboring houses is exactly $1$.


-----Input-----

The first line of the input contains an integer number $n$ — the number of tiers in each cake ($1 \le n \le 10^5$).

The second line contains $2 \cdot n$ integers $a_1, a_2, \dots, a_{2n}$ ($1 \le a_i \le n$), where $a_i$ is equal to the size of the tier, which can be bought in the $i$-th house. Remember that in each house you can buy only one tier. It is guaranteed that every number from $1$ to $n$ occurs in $a$ exactly two times.


-----Output-----

Print one number  — the minimum distance that the guys have to walk in total to buy both cakes. Guys can be near same house at the same time. They begin near the first (leftmost) house. Each of the guys should buy $n$ tiers in ascending order of their sizes.


-----Examples-----
Input
3
1 1 2 2 3 3

Output
9

Input
2
2 1 1 2

Output
5

Input
4
4 1 3 2 2 3 1 4

Output
17



-----Note-----

In the first example, the possible optimal sequence of actions is:  Sasha buys a tier of size $1$ near the $1$-st house ($a_1=1$);  Dima goes to the house $2$;  Dima buys a tier of size $1$ near the $2$-nd house ($a_2=1$);  Sasha goes to the house $4$;  Sasha buys a tier of size $2$ near the $4$-th house ($a_4=2$);  Sasha goes to the house $5$;  Sasha buys a tier of size $3$ near the $5$-th house ($a_5=3$);  Dima goes to the house $3$;  Dima buys a tier of size $2$ near the $3$-rd house ($a_3=2$);  Dima goes to the house $6$;  Dima buys a tier of size $3$ near the $6$-th house ($a_6=3$). 

So, Sasha goes the distance $3+1=4$, and Dima goes the distance $1+1+3=5$. In total, they cover a distance of $4+5=9$. You can make sure that with any other sequence of actions they will walk no less distance.

Difficulty: interview

Starter code:

Solutions:
n = int(input())
a = list(map(int, input().split()))
s = d = 0
m = {i: [] for i in range(1, n + 1)}
for i in range(n):
    m[a[i]] += [i]
for i in range(n, 2 * n):
    m[a[i]] += [i]
res = 0
for i in sorted(m):
    if s > d:
        s, d = d, s
    a, b = m[i]
    if a > b:
        a, b = b, a
    res += abs(s - a) + abs(b - d)
    s, d = a, b
print(res)

n = int(input())
a = [int(i) for i in input().split()]
t = [[] for i in range(n + 1)]
t[0] = [0, 0]
for i in range(2 * n):
    t[a[i]].append(i)
su = 0
# print(t)
for i in range(1, n + 1):
    su += abs(t[i][0] - t[i - 1][0]) + abs(t[i][1] - t[i - 1][1])
print(su)

from collections import defaultdict as dd
import math
def nn():
	return int(input())

def li():
	return list(input())

def mi():
	return list(map(int, input().split()))

def lm():
	return list(map(int, input().split()))


n=nn()

l=lm()

d={}
for i in range(2*n):
	if l[i] in d:
		d[l[i]].append(i)
	else:
		d[l[i]]=[i]



s1=0
s2=0
tot=0

for i in range(n):
	d1=d[i+1][0]
	d2=d[i+1][1]
	dist=min(abs(s1-d1)+abs(s2-d2),abs(s1-d2)+abs(s2-d1))
	tot=tot+dist
	s1=d1
	s2=d2

print(tot)









n=int(input())
a=list(map(int,input().split()))
res=[[] for i in range(n)]
for i in range(2*n):
    res[a[i]-1].append(i)
last1=0
last2=0
su=0
for i in range(n):
    su+=min(abs(last1-res[i][0])+abs(last2-res[i][1]),abs(last1-res[i][1])+abs(last2-res[i][0]))
    last1=res[i][0]
    last2=res[i][1]
print(su)


n = int(input())
a = list(map(int, input().split()))

d = {}

for i in range(1, n+1):
    d[i] = []

for i in range(2*n):
    d[a[i]].append(i)

p1=p2=0
ans = 0
for i in range(1, n+1):
    d1,d2 = d[i][0], d[i][1]
    ans += min([abs(d1-p1) + abs(d2-p2), abs(d2-p1) + abs(d1-p2)])
    p1,p2 = d1, d2
print(ans)

N = int(input())
A = [int(a) for a in input().split()]
L = [-1] * N
R = [0] * N

for i in range(2*N):
    a = A[i] - 1
    if L[a] < 0:
        L[a] = i
    else:
        R[a] = i

s = L[0]+R[0]
for i in range(N-1):
    s += abs(L[i+1] - L[i]) + abs(R[i+1] - R[i])

print(s)


n = int(input())
l = [*map(int, input().split())]
s = set()
l1, l2 = [], []
for i, e in enumerate(l):
    if e in s:
        l2.append((e, i))
    else:
        l1.append((e, i))
        s.add(e)

l1.sort()
l2.sort()

res = 0

prev = 0
for e, i in l1:
    res += abs(i - prev)
    prev = i
prev = 0
for e, i in l2:
    res += abs(i - prev)
    prev = i

print(res)

n = int(input())
a = list(map(int, input().split()))

p1 = 0
p2 = 0
total = 0

pos = {}
for i in range(n):
    pos[i] = []

for i, val in enumerate(a):
    pos[val - 1].append(i)

for i in range(n):
    d1, d2 = pos[i]

    if p1 > p2:
        p1, p2 = p2, p1

    total += abs(p1 - d1)
    total += abs(p2 - d2)
    p1, p2 = d1, d2

print(total)

n = int(input())
a = list(map(int, input().split()))
a = [a[i] - 1 for i in range(2 * n)] 
f = [-1] * n
l = [-1] * n
for i in range(2 * n):
    if f[a[i]] == -1:
        f[a[i]] = i
    else:
        l[a[i]] = i
ans = 0
cur = 0
for i in range(n):
    ans += abs(f[i] - cur)
    cur = f[i]
cur = 0
for i in range(n):
    ans += abs(l[i] - cur)
    cur = l[i]
print(ans)

n=int(input())
d1={}
d2={}
a=list(map(int,input().split()))
for i in range(2*n):
	if a[i] not in d1:
		d1[a[i]]=i
	else:
		d2[a[i]]=i
ans=abs(d1[1])
ans+=abs(d2[1])
for i in range(2,n+1):
	ans+=abs(d1[i]-d1[i-1])
	ans+=abs(d2[i]-d2[i-1])
print(ans)


n = input()
n = int(n)
a = input()
a = a.split()
a = [int(i) for i in a]
num = []
for _ in range(n):
    num.append(list())
for _, i in enumerate(a):
    num[i-1].append(_)
answer = num[0][0] + num[0][1]
for n in range(len(num)-1):
    answer = answer + min(abs(num[n][0] - num[n+1][0]) + abs(num[n][1] - num[n+1][1]),
                          abs(num[n][0] - num[n+1][1]) + abs(num[n][1] - num[n+1][0]))
print(answer)

def B():
    n = int(input())
    a = [int(x) for x in input().split()]
    d = {i:[] for i in range(1,n+1)}
    d[0]= [0,0]
    for i in range(2*n):
        d[a[i]].append(i)
    ans = 0
    for i in range(n):
        a , b = d[i] , d[i+1]
        ans+= min(abs(b[0]-a[0])+abs(b[1]-a[1]) , abs(b[0]-a[1])+abs(b[1]-a[0]))
    print(ans)

B()



n = int(input())

arr = list(map(int,input().strip().split()))

ans = [[] for i in range(n)]

for i in range(2*n):
    ans[arr[i]-1].append(i)

#print(ans)
an = 0
for i in range(n):
    if i==0:
        an+=ans[i][0]+ans[i][1]
    else:
        v1 = abs(ans[i][0]-ans[i-1][0])+abs(ans[i][1]-ans[i-1][1])
        v2 = abs(ans[i][0]-ans[i-1][1])+abs(ans[i][1]-ans[i-1][0])
        an+=min(v1,v2)
print(an)


n = int(input())
ai = list(map(int,input().split()))
ans = 0
dists = [[0,0] for i in range(n+1)]
dists[0][1] = 1
dists[0][0] = 1
j = 1
for i in ai:
    if dists[i][0] == 0:
        dists[i][0] = j
    else:
        dists[i][1] = j
    j += 1
for i in range(n):
    ans += min(abs(dists[i][0] - dists[i+1][0]) + abs(dists[i][1] - dists[i+1][1]),
               abs(dists[i][1] - dists[i+1][0]) + abs(dists[i][0] - dists[i+1][1]) )
print(ans)


n = int(input())
a = list(map(int,input().split()))
dict1 = {}
for i in range(1,n+1):
	dict1[i] = []
for count,i in enumerate(a):
	dict1[i].append(count)
ans = 0
d = 0
s = 0
for i in range(1,n+1):
	ans += abs(d - max(dict1[i]))
	ans += abs(s - min(dict1[i]))
	d = max(dict1[i])
	s = min(dict1[i])
print(ans)

def dist(x, xn):
    return max(x, xn) - min(x, xn)


n = int(input())
b = [[] for _ in range(n + 2)]
i = 1
for a in input().split():
    b[int(a)].append(i)
    i += 1
d = s = 1
res = 1
for a in range(1, n + 1):
    b[a].sort()
    dn, sn = b[a]
    res += dist(d, dn) + dist(s, sn)
    d, s = dn, sn
print(res - 1)


''' CODED WITH LOVE BY SATYAM KUMAR '''


from sys import stdin, stdout
import cProfile, math
from collections import Counter
from bisect import bisect_left,bisect,bisect_right
import itertools
from copy import deepcopy
from fractions import Fraction
import sys, threading
import operator as op
from functools import reduce
sys.setrecursionlimit(10**6) # max depth of recursion
threading.stack_size(2**27)  # new thread will get stack of such size
fac_warmup = False
printHeap = str()
memory_constrained = False
P = 10**9+7
import sys

class Operation:
    def __init__(self, name, function, function_on_equal, neutral_value=0):
        self.name = name
        self.f = function
        self.f_on_equal = function_on_equal
def add_multiple(x, count):
    return x * count
def min_multiple(x, count):
    return x
def max_multiple(x, count):
    return x
sum_operation = Operation("sum", sum, add_multiple, 0)
min_operation = Operation("min", min, min_multiple, 1e9)
max_operation = Operation("max", max, max_multiple, -1e9)
class SegmentTree:
    def __init__(self,
                 array,
                 operations=[sum_operation, min_operation, max_operation]):
        self.array = array
        if type(operations) != list:
            raise TypeError("operations must be a list")
        self.operations = {}
        for op in operations:
            self.operations[op.name] = op
        self.root = SegmentTreeNode(0, len(array) - 1, self)
    def query(self, start, end, operation_name):
        if self.operations.get(operation_name) == None:
            raise Exception("This operation is not available")
        return self.root._query(start, end, self.operations[operation_name])
    def summary(self):
        return self.root.values
    def update(self, position, value):
        self.root._update(position, value)
    def update_range(self, start, end, value):
        self.root._update_range(start, end, value)
    def __repr__(self):
        return self.root.__repr__()
class SegmentTreeNode:
    def __init__(self, start, end, segment_tree):
        self.range = (start, end)
        self.parent_tree = segment_tree
        self.range_value = None
        self.values = {}
        self.left = None
        self.right = None
        if start == end:
            self._sync()
            return
        self.left = SegmentTreeNode(start, start + (end - start) // 2,
                                    segment_tree)
        self.right = SegmentTreeNode(start + (end - start) // 2 + 1, end,
                                     segment_tree)
        self._sync()
    def _query(self, start, end, operation):
        if end < self.range[0] or start > self.range[1]:
            return None
        if start <= self.range[0] and self.range[1] <= end:
            return self.values[operation.name]
        self._push()
        left_res = self.left._query(start, end,
                                    operation) if self.left else None
        right_res = self.right._query(start, end,
                                      operation) if self.right else None
        if left_res is None:
            return right_res
        if right_res is None:
            return left_res
        return operation.f([left_res, right_res])
    def _update(self, position, value):
        if position < self.range[0] or position > self.range[1]:
            return
        if position == self.range[0] and self.range[1] == position:
            self.parent_tree.array[position] = value
            self._sync()
            return
        self._push()
        self.left._update(position, value)
        self.right._update(position, value)
        self._sync()
    def _update_range(self, start, end, value):
        if end < self.range[0] or start > self.range[1]:
            return
        if start <= self.range[0] and self.range[1] <= end:
            self.range_value = value
            self._sync()
            return
        self._push()
        self.left._update_range(start, end, value)
        self.right._update_range(start, end, value)
        self._sync()
    def _sync(self):
        if self.range[0] == self.range[1]:
            for op in self.parent_tree.operations.values():
                current_value = self.parent_tree.array[self.range[0]]
                if self.range_value is not None:
                    current_value = self.range_value
                self.values[op.name] = op.f([current_value])
        else:
            for op in self.parent_tree.operations.values():
                result = op.f(
                    [self.left.values[op.name], self.right.values[op.name]])
                if self.range_value is not None:
                    bound_length = self.range[1] - self.range[0] + 1
                    result = op.f_on_equal(self.range_value, bound_length)
                self.values[op.name] = result
    def _push(self):
        if self.range_value is None:
            return
        if self.left:
            self.left.range_value = self.range_value
            self.right.range_value = self.range_value
            self.left._sync()
            self.right._sync()
            self.range_value = None
    def __repr__(self):
        ans = "({}, {}): {}\n".format(self.range[0], self.range[1],
                                      self.values)
        if self.left:
            ans += self.left.__repr__()
        if self.right:
            ans += self.right.__repr__()
        return ans

def display(string_to_print):
    stdout.write(str(string_to_print) + "\n")

def primeFactors(n): #n**0.5 complex 
    factors = dict()
    for i in range(2,math.ceil(math.sqrt(n))+1):  
        while n % i== 0: 
            if i in factors:
                factors[i]+=1
            else: factors[i]=1
            n = n // i 
    if n>2:
        factors[n]=1
    return (factors)

def binary(n,digits = 20):
    b = bin(n)[2:]
    b = '0'*(20-len(b))+b
    return b

def isprime(n):
    """Returns True if n is prime."""
    if n < 4:
        return True
    if n % 2 == 0:
        return False
    if n % 3 == 0:
        return False
    i = 5
    w = 2
    while i * i <= n:
        if n % i == 0:
            return False
        i += w
        w = 6 - w
    return True
factorial_modP = []
def warm_up_fac(MOD):
    nonlocal factorial_modP,fac_warmup
    if fac_warmup: return
    factorial_modP= [1 for _ in range(fac_warmup_size+1)]
    for i in range(2,fac_warmup_size):
        factorial_modP[i]= (factorial_modP[i-1]*i) % MOD
    fac_warmup = True

def InverseEuler(n,MOD):
    return pow(n,MOD-2,MOD)

def nCr(n, r, MOD):
    nonlocal fac_warmup,factorial_modP
    if not fac_warmup:
        warm_up_fac(MOD)
        fac_warmup = True
    return (factorial_modP[n]*((pow(factorial_modP[r], MOD-2, MOD) * pow(factorial_modP[n-r], MOD-2, MOD)) % MOD)) % MOD

def test_print(*args):
    if testingMode:
        print(args)

def display_list(list1, sep=" "):
    stdout.write(sep.join(map(str, list1)) + "\n")

def get_int():
    return int(stdin.readline().strip())

def get_tuple():
    return map(int, stdin.readline().split())

def get_list():
    return list(map(int, stdin.readline().split()))
import heapq,itertools
pq = []                         # list of entries arranged in a heap
entry_finder = {}               # mapping of tasks to entries
REMOVED = '<removed-task>' 
def add_task(task, priority=0):
    'Add a new task or update the priority of an existing task'
    if task in entry_finder:
        remove_task(task)
    count = next(counter)
    entry = [priority, count, task]
    entry_finder[task] = entry
    heapq.heappush(pq, entry)

def remove_task(task):
    'Mark an existing task as REMOVED.  Raise KeyError if not found.'
    entry = entry_finder.pop(task)
    entry[-1] = REMOVED

def pop_task():
    'Remove and return the lowest priority task. Raise KeyError if empty.'
    while pq:
        priority, count, task = heapq.heappop(pq)
        if task is not REMOVED:
            del entry_finder[task]
            return task
    raise KeyError('pop from an empty priority queue')
memory = dict()
def clear_cache():
    nonlocal memory
    memory = dict()
def cached_fn(fn, *args):
    nonlocal memory
    if args in memory:
        return memory[args]
    else:
        result = fn(*args)
        memory[args] = result
        return result
def binary_serach(i,li):
    #print("Search for ",i)
    fn = lambda x: li[x]-x//i
    x = -1
    b = len(li)
    while b>=1:
        #print(b,x)
        while b+x<len(li) and fn(b+x)>0: #Change this condition 2 to whatever you like
            x+=b
        b=b//2
    return x

# -------------------------------------------------------------- MAIN PROGRAM
TestCases = False
testingMode = False
fac_warmup_size = 10**5+100
optimiseForReccursion = True #Can not be used clubbed with TestCases

def main():
    n = get_int()
    li =get_list()
    ind = [[] for _ in range(n)]
    for i,ele in enumerate(li):
        ind[ele-1].append(i)
    res = 0
    for pas in [0,1]:
        p = 0
        for i in range(n):
            res+=abs(p-ind[i][pas])
            p = ind[i][pas]
    print(res)
# --------------------------------------------------------------------- END=


if TestCases: 
    for _ in range(get_int()): 
        cProfile.run('main()') if testingMode else main() 
else: (cProfile.run('main()') if testingMode else main()) if not optimiseForReccursion else threading.Thread(target=main).start()

#!/bin/python3

import math
import os
import random
import re
import sys

n=int(input())
l=list(map(int,input().split()))
d={}
for i in range(2*n):
    if d.get(l[i],0)==0:
        t=[]
        t.append(i)
        d[l[i]]=t
    else:
        d[l[i]].append(i)
a,b=0,0
c,e=0,0
k=0
for i in sorted(d.keys()):
    z = sorted(d[i])
    if k==0:
        a=abs(a-z[0])
        b=abs(b-z[1])
    else:
        a+=abs(c-z[0])
        b+=abs(e-z[1])
    c=z[0]
    e=z[1]
    k+=1
print(a+b)
    



n = int(input())
A = [int(i) for i in input().split()]

X = [[] for i in range(n+1)]

for i, a in enumerate(A):
    X[a].append(i)

Sasha = 0
Dima = 0
ans = 0
for i in range(1, n+1):
    d1 = abs(Sasha - X[i][0]) + abs(Dima - X[i][1])
    d2 = abs(Sasha - X[i][1]) + abs(Dima - X[i][0])
    if d1 < d2:
        ans += d1
        Sasha = X[i][0]
        Dima = X[i][1]
    else:
        ans += d2
        Sasha = X[i][1]
        Dima = X[i][0]

print(ans)

from math import ceil 
n = int(input()) 
a = list(map(int, input().split())) 
cur_state_sasha = 0
cur_state_dima = 0 
a = [(p,i) for i,p in enumerate(a)] 
a.sort() 
ans = 0
for i in range(0 , 2*n , 2):
	ans += abs(a[i][1] - cur_state_sasha) 
	cur_state_sasha = a[i][1] 
	ans += abs(a[i+1][1] - cur_state_dima)
	cur_state_dima = a[i+1][1] 
	# print(ans)

print(ans)

n = int(input())
nums = [int(x) for x in input().split()]

coords = {}

for i, k in enumerate(nums):
    if str(k) + "_1" in coords:
        coords[str(k) + "_2"] = i
    else:
        coords[str(k) + "_1"] = i

#print(coords)

s = 0
prev1 = 0
prev2 = 0
for i in range(1, n+1):
    cur1 = coords[str(i) + "_1"]
    cur2 = coords[str(i) + "_2"]
    #print(prev1, prev2, cur1, cur2)
    d1 = abs(cur1 - prev1) + abs(cur2 - prev2)
    d2 = abs(cur1 - prev2) + abs(cur2 - prev1)
    #print("d1 ", d1, "d2 ", d2)
    s += min(d1, d2)
    prev1 = cur1
    prev2 = cur2
    #print(s)

print(s)


n = int(input())
a = [int(x) for x in input().split()]
f = {}
for i, x in enumerate(a):
  if x not in f:
    f[x] = [i]
  else:
    f[x].append(i)
    f[x].sort()

l = 0
cnt = 0
r = 0
for i in range(1, n + 1):
  if abs(f[i][0] - l) + abs(f[i][1] - r) < abs(f[i][1] - l) + abs(f[i][0] - r):
    cnt += abs(f[i][0] - l)
    l = f[i][0]
    cnt += abs(f[i][1] - r)
    r = f[i][1]
  else:
    cnt += abs(f[i][1] - l)
    l = f[i][1]
    cnt += abs(f[i][0] - r)
    r = f[i][0]

print(cnt)

n=int(input())
arr=list(map(int,input().split()))
dict1={}
for i in range(2*n):
	try:
		dict1[arr[i]].append(i+1)
		dict1[arr[i]].sort()
	except:
		KeyError
		dict1[arr[i]]=[i+1]
ans=0
curr1=1
curr2=1
for i in range(1,n+1):
	if(i==1):
		ans+=(dict1[i][0]-curr1)
		ans+=(dict1[i][1]-curr2)
		curr1=dict1[i][0]
		curr2=dict1[i][1]
	elif(dict1[i][0]>curr1 and dict1[i][0]>curr2):
		ans+=(dict1[i][0]-curr1)
		ans+=(dict1[i][1]-curr2)
		curr1=dict1[i][0]
		curr2=dict1[i][1]
	elif(dict1[i][1]<curr1<curr2):
		ans+=abs(dict1[i][0]-curr1)
		ans+=abs(dict1[i][1]-curr2)
		curr1=dict1[i][0]
		curr2=dict1[i][1]
	elif(dict1[i][0]<curr1 and curr1<dict1[i][1]<curr2):
		ans+=abs(dict1[i][0]-curr1)
		ans+=abs(dict1[i][1]-curr2)
		curr1=dict1[i][0]
		curr2=dict1[i][1]
	elif(dict1[i][0]<curr1 and dict1[i][1]<curr2):
		ans+=abs(dict1[i][0]-curr1)
		ans+=abs(dict1[i][1]-curr2)
		curr1=dict1[i][0]
		curr2=dict1[i][1]
	elif(curr1<dict1[i][0]<dict1[i][1]<curr2):
		ans+=abs(dict1[i][0]-curr1)
		ans+=abs(dict1[i][1]-curr2)
		curr1=dict1[i][0]
		curr2=dict1[i][1]
	else:
		ans+=abs(dict1[i][0]-curr1)
		ans+=abs(dict1[i][1]-curr2)
		curr1=dict1[i][0]
		curr2=dict1[i][1]
print(ans)