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: EASY
Tags: Greedy algorithms
Skill types: Greedy algorithms

Starter code:

Solutions:
n = int(input())
numbers = map(int, input().split())
indexed_numbers = zip(numbers, range(n * 2))
indexed_numbers = list(sorted(indexed_numbers, key=lambda x: x[0], reverse=True))
cur_a = 0
cur_b = 0
total = 0
while len(indexed_numbers) > 0:
	next_a = indexed_numbers.pop(-1)[1]
	next_b = indexed_numbers.pop(-1)[1]
	total += min(abs(cur_a - next_a) + abs(cur_b - next_b), abs(cur_a - next_b) + abs(cur_b - next_a))
	cur_a = next_a
	cur_b = next_b
print(total)


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


n = int(input())
a = [int(x) for x in input().split()]
dic = {}
i = 1
for item in a:
	if item not in dic:
		dic[item] = [i]
	else:
		dic[item].append(i)
	i += 1
counter = 0
i = j = 1
for item in range(1, n + 1):
	if abs(dic[item][0] - i) + abs(dic[item][1] - j) >= abs(dic[item][1] - i) + abs(dic[item][0] - j):
		counter += abs(dic[item][1] - i) + abs(dic[item][0] - j)
		i = dic[item][1]
		j = dic[item][0]
	else:
		counter += abs(dic[item][0] - i) + abs(dic[item][1] - j)
		i = dic[item][0]
		j = dic[item][1]
print(counter)


from collections import defaultdict
n = int(input())
a = list(map(int, input().split()))
d = defaultdict(list)
for i in range(2 * n):
	d[a[i]].append(i + 1)
a = 0
b = 0
ans = 0
for i in range(n):
	t1 = abs(d[i + 1][0] - a) + abs(d[i + 1][1] - b)
	t2 = abs(d[i + 1][0] - b) + abs(d[i + 1][1] - a)
	if t1 > t2:
		ans += t2
		a = d[i + 1][1]
		b = d[i + 1][0]
	else:
		ans += t1
		a = d[i + 1][0]
		b = d[i + 1][1]
print(ans - 2)


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


n = int(input())
a = list(map(int, input().split()))
b = [-1] * (n + 1)
c = [-1] * (n + 1)
for i in range(2 * n):
	if b[a[i]] == -1:
		b[a[i]] = i
	else:
		c[a[i]] = i
jb = 0
jc = 0
res = 0
for i in range(1, n + 1):
	res = res + abs(b[i] - jb) + abs(c[i] - jc)
	jb = b[i]
	jc = c[i]
print(res)


n = int(input())
s = list(zip(*sorted(zip(list(map(int, input().split())), [i for i in range(1, 2 * n + 1)]))))[1]
r = s[0] + s[1] - 2
for i in range(n - 1):
	r += min(abs(s[2 * i + 2] - s[2 * i]) + abs(s[2 * i + 3] - s[2 * i + 1]), abs(s[2 * i + 2] - s[2 * i + 1]) + abs(s[2 * i + 3] - s[2 * i]))
print(r)


from collections import defaultdict

def solve():
	n = int(input())
	nums = list(map(int, input().split()))
	stores = defaultdict(list)
	for (index, num) in enumerate(nums, 0):
		stores[num - 1].append(index)
	total = 0
	(da, db) = (0, 0)
	for i in range(n):
		(na, nb) = stores[i]
		total += min(abs(da - na) + abs(db - nb), abs(da - nb) + abs(db - na))
		(da, db) = (na, nb)
	print(total)
solve()


n = int(input().strip())
arr = list(map(int, input().strip().split()))
pos = [[] for i in range(n)]
for i in range(2 * n):
	pos[arr[i] - 1].append(i)
pos = [[0, 0]] + pos
res = 0
for i in range(1, n + 1):
	(a, b) = pos[i - 1]
	(c, d) = pos[i]
	res += min(abs(a - c) + abs(b - d), abs(a - d) + abs(b - c))
print(res)


n = int(input())
l = list(map(int, input().split()))
k = sorted(enumerate(l), key=lambda x: x[1])
s = 0
d = 0
count = 0
n = 2 * n
for i in range(0, n - 1, 2):
	(x, y) = k[i]
	(q, w) = k[i + 1]
	m = abs(x - s) + abs(q - d)
	n = abs(x - d) + abs(q - s)
	if m <= n:
		s = x
		d = q
		count += m
	elif m > n:
		s = q
		d = x
		count += n
print(count)


n = int(input())
ar = [int(x) for x in input().split()]
ma = {}
for (idx, v) in enumerate(ar):
	ma[v] = ma.get(v, []) + [idx]
dist = sum(ma[1])
for idx in range(2, n + 1):
	dist = dist + min(abs(ma[idx][1] - ma[idx - 1][1]) + abs(ma[idx][0] - ma[idx - 1][0]), abs(ma[idx][1] - ma[idx - 1][0]) + abs(ma[idx][0] - ma[idx - 1][1]))
print(dist)


from __future__ import division, print_function
import os
import sys
from atexit import register
from io import StringIO
sys.stdin = StringIO(os.read(0, os.fstat(0).st_size).decode())
sys.stdout = StringIO()
register(lambda : os.write(1, sys.stdout.getvalue().encode()))

def cinput():
	return sys.stdin.readline().rstrip('\r\n')

class Guy:
	n = 0

	def __init__(self):
		self.got = 0
		self.passed = {}
		self.pos = 0

	def update(self, i, k) -> bool:
		if k == self.got + 1 and k not in self.passed:
			(self.got, self.pos) = (k, i)
			return True
		elif k > self.got and k not in self.passed:
			self.passed[k] = i
			return True
		return False

	def getPassed(self):
		distance = self.pos
		for k in range(self.got + 1, Guy.n + 1):
			distance += abs(self.pos - self.passed[k])
			self.pos = self.passed.pop(k)
		return distance

def main():
	Guy.n = int(cinput())
	nums = (int(num) for num in cinput().split())
	(sasha, dima) = (Guy(), Guy())
	guys = (sasha, dima)
	for (i, num) in enumerate(nums):
		for guy in guys:
			if guy.update(i, num):
				break
	print(sum((guy.getPassed() for guy in guys)))
main()


(n,) = map(int, input().split())
a = list(map(int, input().split()))
L = [[] for i in range(0, n)]
for i in range(0, 2 * n):
	L[a[i] - 1].append(i)
(f, s) = (0, 0)
dis = 0
for i in range(0, n):
	(p1, p2) = (L[i][0], L[i][1])
	if abs(p1 - f) + abs(p2 - s) <= abs(p2 - f) + abs(p1 - s):
		dis += abs(p1 - f) + abs(p2 - s)
		(f, s) = (p1, p2)
	else:
		dis += abs(p2 - f) + abs(p1 - s)
		(f, s) = (p2, p1)
print(dis)


n = int(input())
s = [int(x) for x in input().split()]
k1 = [-1] * n
k2 = [-1] * n
for i in range(0, len(s)):
	if k1[s[i] - 1] == -1:
		k1[s[i] - 1] = i
	else:
		k2[s[i] - 1] = i
ans = 0
for i in range(0, n - 1):
	t1 = abs(k1[i] - k1[i + 1]) + abs(k2[i] - k2[i + 1])
	t2 = abs(k1[i] - k2[i + 1]) + abs(k2[i] - k1[i + 1])
	ans = ans + min(t1, t2)
print(ans + k1[0] + k2[0])


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


from sys import stdin
from math import ceil
n = int(stdin.readline().strip())
s = list(map(int, stdin.readline().strip().split()))
dp = [[] for i in range(n + 1)]
for i in range(2 * n):
	dp[s[i]].append(i)
ans = 0
ans += sum(dp[1])
d = dp[1][0]
d1 = dp[1][1]
for i in range(2, n + 1):
	dn = dp[i][0]
	dn1 = dp[i][1]
	x = abs(dn - d) + abs(d1 - dn1)
	y = abs(dn - d1) + abs(d - dn1)
	if y < x:
		ans += y
		d1 = dn
		d = dn1
	else:
		ans += x
		d = dn
		d1 = dn1
print(ans)


n = int(input())
a = list(map(int, input().split()))
d = {}
for i in range(2 * n):
	if a[i] not in d:
		d[a[i]] = [i]
	else:
		d[a[i]].append(i)
diff = 0
d[0] = [0, 0]
for i in range(n):
	diff += min(abs(d[i][0] - d[i + 1][0]) + abs(d[i][1] - d[i + 1][1]), abs(d[i][1] - d[i + 1][0]) + abs(d[i][0] - d[i + 1][1]))
print(diff)


n = int(input())
lst = list(map(int, input().split()))
d = {}
for (i, x) in enumerate(lst):
	if d.get(x) == None:
		d[x] = []
	d[x].append(i)
res = d[1][0] + d[1][1]
(x1, y1) = (d[1][0], d[1][1])
for i in range(2, n + 1):
	(x2, y2) = (d[i][0], d[i][1])
	res += min(abs(x2 - x1) + abs(y2 - y1), abs(x2 - y1) + abs(y2 - x1))
	(x1, y1) = (x2, y2)
print(res)


from sys import exit, setrecursionlimit
setrecursionlimit(10 ** 6)
inn = lambda : input().strip()
mapp = lambda : map(int, inn().split(' '))
N = int(inn())
arr = list(enumerate(mapp()))
arr.sort(key=lambda x: x[1])
answer = 0
sasha = dima = 0
for i in range(0, len(arr), 2):
	(sasha_A, sasha_B) = (abs(sasha - arr[i][0]), abs(sasha - arr[i + 1][0]))
	(dima_A, dima_B) = (abs(dima - arr[i][0]), abs(dima - arr[i + 1][0]))
	if sasha_A + dima_B < sasha_B + dima_A:
		answer += sasha_A
		answer += dima_B
		sasha = arr[i][0]
		dima = arr[i + 1][0]
	else:
		answer += sasha_B
		answer += dima_A
		sasha = arr[i + 1][0]
		dima = arr[i][0]
print(answer)


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)


R = lambda : map(int, input().split())
n = int(input())
L = list(R())
d = [[0, 0]] + [[] for i in range(n)]
for (j, i) in enumerate(L):
	d[i].append(j)
res = 0
for i in range(1, n + 1):
	res += abs(d[i][0] - d[i - 1][0]) + abs(d[i][1] - d[i - 1][1])
print(res)


from sys import stdin, stdout
from collections import Counter

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

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

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

def op(ans):
	return stdout.write(str(ans) + '\n')
from math import ceil
n = ip()
li = ai()
new = []
for i in range(2 * n):
	new.append((li[i], i))
new.sort()
sasha = new[0][1]
dim = new[1][1]
for i in range(2, 2 * n):
	if i % 2 == 0:
		sasha += abs(new[i][1] - new[i - 2][1])
	else:
		dim += abs(new[i][1] - new[i - 2][1])
print(sasha + dim)


a = [() for _ in [0] * int(input())]
i = 0
for x in map(int, input().split()):
	a[x - 1] += (i,)
	i += 1
s = d = 0
for ((u, v), (x, y)) in zip([(0, 0)] + a, a):
	d += abs(x - u)
	s += abs(y - v)
print(s + d)


ii = lambda : int(input())
mi = lambda : map(int, input().split())
li = lambda : list(mi())
n = ii()
l = li()
d = {}
d.update({0: [1, 1]})
for (i, j) in enumerate(l, 1):
	try:
		d[j][1] = i
	except KeyError:
		d[j] = [i, -1]
c = 0
(xi, yi) = d[0]
for i in range(1, len(d)):
	c += min(abs(xi - d[i][0]) + abs(yi - d[i][1]), abs(xi - d[i][1]) + abs(yi - d[i][0]))
	(xi, yi) = d[i]
print(c)


n = int(input())
a = list(map(int, input().strip().split()))
b = []
for i in range(n * 2):
	b.append([a[i], i + 1])
b.sort()
c = 0
for j in range(n - 1):
	c = c + abs(b[(j + 1) * 2][1] - b[j * 2][1])
for k in range(n - 1):
	c = c + abs(b[(k + 1) * 2 + 1][1] - b[k * 2 + 1][1])
print(c + b[1][1] - 1 + b[0][1] - 1)


(n, a) = (int(input()), [(int(x), i) for (i, x) in enumerate(input().split())])
a.sort()
a = [[x[1] for x in a[i::2]] for i in range(2)]
print(sum((a[i][0] + sum([abs(a[i][j] - a[i][j - 1]) for j in range(1, n)]) for i in range(2))))


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 = int(input())
a = list(map(int, input().split()))
p = 0
q = 0
dict = {}
for i in range(1, n + 1):
	dict[i] = []
for i in range(0, 2 * n):
	dict[a[i]].append(i)
k = 0
l = 0
for i in range(1, n + 1):
	p += abs(k - dict[i][0])
	q += abs(l - dict[i][1])
	k = dict[i][0]
	l = dict[i][1]
print(p + q)


n = int(input())
a = [int(i) for i in input().split()]
b = []
for i in range(2 * n):
	b.append([a[i], i + 1])
b.sort()
for i in range(2 * n):
	if b[i][1] == 1:
		k = i
		break
ans = b[0][1] - b[k][1] + (b[1][1] - b[k][1])
for i in range(2, 2 * n, 2):
	ans += abs(b[i][1] - b[i - 2][1]) + abs(b[i + 1][1] - b[i - 1][1])
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)


from collections import defaultdict
n = int(input())
a = map(int, input().split())
d = defaultdict(list)
for i in range(2 * n):
	tmp = next(a)
	d[tmp].append(i + 1)
pos1 = 1
pos2 = 1
ans = 0
for t in range(1, n + 1):
	l = d[t][0]
	r = d[t][1]
	ans += abs(pos1 - l) + abs(pos2 - r)
	pos1 = l
	pos2 = r
print(ans)


n = int(input())
a = list(map(int, input().split()))
d = {}
for i in range(2 * n):
	if a[i] in d:
		d[a[i]].append(i)
	else:
		d[a[i]] = [i]
out = 0
z = a.index(1)
out += z
z += 1
out += z + a[z:].index(1)
for i in range(1, n):
	out += min(abs(d[i + 1][0] - d[i][0]) + abs(d[i + 1][1] - d[i][1]), abs(d[i + 1][0] - d[i][1]) + abs(d[i + 1][1] - d[i][0]))
print(out)


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)


from math import sqrt
import heapq

def main():
	n = int(input())
	a = [int(x) for x in input().split(' ')]
	spots = [[] for i in range(n + 1)]
	for (i, k) in enumerate(a):
		spots[k].append(i)
	spots[0].extend([0, 0])
	ans = 0
	for i in range(1, n + 1):
		cur1 = abs(spots[i][0] - spots[i - 1][0]) + abs(spots[i][1] - spots[i - 1][1])
		cur2 = abs(spots[i][0] - spots[i - 1][1]) + abs(spots[i][1] - spots[i - 1][0])
		ans += min(cur1, cur2)
	print(ans)
main()


from operator import itemgetter
n = int(input())
listing = list(input().split())
dictionary = {}
counter = 1
for i in listing:
	if i not in dictionary:
		dictionary[i] = []
	dictionary[i].append(counter)
	counter += 1
prev_temp1 = 1
prev_temp2 = 1
cost = 0
for i in range(1, n + 1):
	i = str(i)
	cost += abs(min(dictionary[i]) - prev_temp1) + abs(max(dictionary[i]) - prev_temp2)
	prev_temp1 = min(dictionary[i])
	prev_temp2 = max(dictionary[i])
print(cost)


import sys
input = sys.stdin.readline
n = int(input())
a = list(map(int, input().split()))
sold = [False] * 2 * n
pos = [[] for _ in range(n + 1)]
for i in range(2 * n):
	pos[a[i]].append(i)
	if len(pos[a[i]]) == 2:
		pos[a[i]].sort()
sasha = dima = 1
p1 = p2 = ret = 0
while sasha <= n and dima <= n:
	dist = 1000000000
	for i in pos[sasha]:
		for j in pos[dima]:
			if i == j:
				continue
			t = abs(i - p1) + abs(j - p2)
			if t < dist:
				dist = t
				(resi, resj) = (i, j)
	ret += dist
	(p1, p2) = (resi, resj)
	sasha = dima = dima + 1
print(ret)


n = int(input())
a = list(map(int, input().split(' ')))
poses = [0] * (n * 2 + 2)
pos = 1
for v in a:
	if poses[v * 2] == 0:
		poses[v * 2] = pos
	else:
		poses[v * 2 + 1] = pos
	pos += 1
(ap, bp) = (1, 1)

def posesof(v):
	global poses
	return [poses[v * 2], poses[v * 2 + 1]]
s = 0
for i in range(1, n + 1):
	(a, b) = (poses[i * 2], poses[i * 2 + 1])
	if abs(a - ap) + abs(b - bp) < abs(a - bp) + abs(b - ap):
		s += abs(a - ap) + abs(b - bp)
		ap = a
		bp = b
	else:
		s += abs(a - bp) + abs(b - ap)
		ap = b
		bp = a
print(s)


def fastio():
	import sys
	from io import StringIO
	from atexit import register
	global input
	sys.stdin = StringIO(sys.stdin.read())
	input = lambda : sys.stdin.readline().rstrip('\r\n')
	sys.stdout = StringIO()
	register(lambda : sys.__stdout__.write(sys.stdout.getvalue()))
fastio()
MOD = 10 ** 9 + 7
I = lambda : list(map(int, input().split()))
(n,) = I()
l = I()
for i in range(2 * n):
	l[i] = (l[i], i)
l.sort()
ans = l[0][1] + l[1][1]
for i in range(2, 2 * n, 2):
	ans += abs(l[i - 2][1] - l[i][1]) + abs(l[i - 1][1] - l[i + 1][1])
print(ans)


n = int(input())
lst = list(map(int, input().split(' ')))
e1 = lambda x: x[1]
iset = sorted([(i, lst[i]) for i in range(2 * n)], key=e1)
way = 0
pos1 = 0
pos2 = 0
for i in range(n):
	d0 = abs(iset[i * 2][0] - pos1) + abs(iset[i * 2 + 1][0] - pos2)
	d1 = abs(iset[i * 2 + 1][0] - pos1) + abs(iset[i * 2][0] - pos2)
	pos1 = iset[i * 2][0]
	pos2 = iset[i * 2 + 1][0]
	way += min(d0, d1)
print(way)


n = int(input())
a = list(map(int, input().split()))
la = [(ai, idx) for (idx, ai) in enumerate(a)]
sla = sorted(la)
sasha = 0
sasha_pos = 0
sasha_yar = 0
exclude = set()
for (idx, ai) in enumerate(sla):
	if ai[0] - sasha_yar == 1:
		exclude.add(idx)
		sasha_yar += 1
		sasha += abs(sasha_pos - ai[1])
		sasha_pos = ai[1]
dima = 0
dima_pos = 0
dima_yar = 0
for ai in [aj for (idx, aj) in enumerate(sla) if not idx in exclude]:
	if ai[0] - dima_yar == 1:
		dima_yar += 1
		dima += abs(dima_pos - ai[1])
		dima_pos = ai[1]
print(sasha + dima)


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(s) for s in input().split()]
a = [0] + a
mesta = [[-1, -1] for s in range(n + 1)]
for i in range(1, len(a)):
	if mesta[a[i]][0] == -1:
		mesta[a[i]][0] = i
	elif mesta[a[i]][0] != -1 and mesta[a[i]][1] == -1:
		mesta[a[i]][1] = i
place_sasha = 1
place_dima = 1
F = [0] * (n + 1)
for i in range(1, n + 1):
	x = abs(mesta[i][0] - place_sasha) + abs(mesta[i][1] - place_dima)
	y = abs(mesta[i][1] - place_sasha) + abs(mesta[i][0] - place_dima)
	sum = min(x, y)
	if sum == x:
		place_sasha = mesta[i][0]
		place_dima = mesta[i][1]
	else:
		place_sasha = mesta[i][1]
		place_dima = mesta[i][0]
	F[i] = F[i - 1] + sum
print(F[n])


n = int(input())
houses = []
num = 0
for a in input().split(' '):
	houses.append([num, int(a) - 1])
	num += 1
houses.sort(key=lambda a: a[1])
dist = 0
pos0 = 0
pos1 = 0
for i in range(n):
	dist += abs(pos0 - houses[i * 2][0])
	dist += abs(pos1 - houses[i * 2 + 1][0])
	pos0 = houses[i * 2][0]
	pos1 = houses[i * 2 + 1][0]
print(dist)


l1 = []
n = int(input())
l = list(map(int, input().split()))
for i in range(2 * n):
	l1.append([l[i], i])
l1.sort()
(sd, dd) = (l1[0][1], l1[1][1])
for i in range(2, 2 * n):
	if i % 2:
		dd += abs(l1[i][1] - l1[i - 2][1])
	else:
		sd += abs(l1[i][1] - l1[i - 2][1])
print(sd + dd)


n = int(input())
a = [int(v) for v in input().split()]
b = [[] for _ in range(n + 1)]
for i in range(2 * n):
	b[a[i]].append(i + 1)
f = b[1][0] + b[1][1] - 2
for j in range(1, n):
	p = f + abs(b[j][0] - b[j + 1][0]) + abs(b[j][1] - b[j + 1][1])
	q = f + abs(b[j][0] - b[j + 1][1]) + abs(b[j][1] - b[j + 1][0])
	f = min(p, q)
print(f)


n = 2 * int(input())
ln = input().split(' ')
poses = {}
(curx, cury) = (1, 1)
ans = 0
for i in range(n):
	p = int(ln[i])
	if p not in poses:
		poses[p] = [i + 1]
	else:
		poses[p].append(i + 1)
for i in range(n // 2):
	targets = poses[i + 1]
	way1 = abs(targets[0] - curx) + abs(targets[1] - cury)
	way2 = abs(targets[1] - curx) + abs(targets[0] - cury)
	if way1 <= way2:
		ans += way1
		(curx, cury) = (targets[0], targets[1])
	else:
		ans += way2
		(curx, cury) = (targets[1], targets[0])
print(ans)


n = int(input())
a = list(map(int, input().split()))
m = [[] for i in range(n)]
for i in range(2 * n):
	m[a[i] - 1].append(i)
res = 0
(l, r) = (0, 0)
for i in range(n):
	(new_l, new_r) = (min(m[i]), max(m[i]))
	res += abs(new_l - l) + abs(new_r - r)
	l = new_l
	r = new_r
print(res)


i = int(input())
j = list(map(int, input().split()))
ac = 1
bc = 1
x = {}
for k in range(1, i + 1):
	x[k] = []
u = 1
for k in j:
	x[k].append(u)
	u += 1
su = 0
for k in range(1, i + 1):
	t = abs(x[k][0] - ac) + abs(x[k][1] - bc)
	y = abs(x[k][0] - bc) + abs(x[k][1] - ac)
	if t < y:
		su += t
		ac = x[k][0]
		bc = x[k][1]
	else:
		su += y
		ac = x[k][1]
		bc = x[k][0]
print(su)


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


import sys
import math
d1 = {}
d2 = {}
n = sys.stdin.readline()
n = n.replace('\n', '')
n = int(n)
l = sys.stdin.readline()
l = l.split(' ')
l[-1] = l[-1].replace('\n', '')
for i in range(len(l)):
	l[i] = int(l[i])
for i in range(1, n + 1):
	d1[i] = -1
	d2[i] = -1
for i in range(len(l)):
	if d1[l[i]] == -1:
		d1[l[i]] = i
	else:
		d2[l[i]] = i
x1 = d1[1]
for i in range(2, n + 1):
	if d1[i] > d1[i - 1]:
		x1 += d1[i] - d1[i - 1]
	else:
		x1 += d1[i - 1] - d1[i]
x2 = d2[1]
for i in range(2, n + 1):
	if d2[i] > d2[i - 1]:
		x2 += d2[i] - d2[i - 1]
	else:
		x2 += d2[i - 1] - d2[i]
print(x1 + x2)


n = int(input())
a = list(map(int, input().split()))
d = [[] for _ in range(n)]
for i in range(2 * n):
	d[a[i] - 1].append(i)
ans = 0
pos = [0, 0]
for i in range(n):
	ans += min(abs(d[i][0] - pos[0]) + abs(d[i][1] - pos[1]), abs(d[i][1] - pos[0]) + abs(d[i][0] - pos[1]))
	pos = d[i]
print(ans)


def main():
	n = int(input())
	x = []
	t = 0
	for i in map(int, input().split()):
		x.append((i, t))
		t += 1
	x.sort()
	b = x[0][1] + x[1][1]
	for i in range(len(x) - 2):
		b += abs(x[i + 2][1] - x[i][1])
	print(b)
main()


n = int(input())
arr = list(map(int, input().split()))
pos = []
for i in range(n):
	pos.append([-1, -1])
for i in range(2 * n):
	if pos[arr[i] - 1][0] == -1:
		pos[arr[i] - 1][0] = i
	else:
		pos[arr[i] - 1][1] = i
l = 0
sl = 0
tot = 0
for i in range(n):
	tot += abs(pos[i][0] - l)
	tot += abs(pos[i][1] - sl)
	l = pos[i][0]
	sl = pos[i][1]
print(tot)


n = int(input())
arr1 = list(map(int, input().split()))
t = 0
x = []
for i in arr1:
	x.append((i, t))
	t += 1
x.sort()
b = x[0][1] + x[1][1]
for i in range(len(x) - 2):
	b += abs(x[i + 2][1] - x[i][1])
print(b)


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)


import os
import sys
from io import BytesIO, IOBase
from collections import Counter
import math as mt
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))

def gcd(a, b):
	if a == 0:
		return b
	return gcd(b % a, a)

def lcm(a, b):
	return a * b / gcd(a, b)
mod = int(1000000000.0) + 7

def power(k, n):
	if n == 0:
		return 1
	if n % 2:
		return power(k, n - 1) * k % mod
	t = power(k, n // 2)
	return t * t % mod

def totalPrimeFactors(n):
	count = 0
	if n % 2 == 0:
		count += 1
		while n % 2 == 0:
			n //= 2
	i = 3
	while i * i <= n:
		if n % i == 0:
			count += 1
			while n % i == 0:
				n //= i
		i += 2
	if n > 2:
		count += 1
	return count

def main():
	n = int(input())
	a = list(map(int, input().split()))
	d = {}
	for i in range(2 * n):
		if a[i] not in d.keys():
			d[a[i]] = []
		d[a[i]].append(i)
	f = 0
	s = 0
	ans = 0
	for i in range(1, n + 1):
		if abs(f - d[i][0]) + abs(s - d[i][1]) <= abs(f - d[i][1]) + abs(s - d[i][0]):
			ans += abs(f - d[i][0]) + abs(s - d[i][1])
			f = d[i][0]
			s = d[i][1]
		else:
			ans += abs(f - d[i][1]) + abs(s - d[i][0])
			f = d[i][1]
			s = d[i][0]
	print(ans)
	return
main()


n = int(input())
a = [int(i) for i in input().split(' ')]
import collections
lookup = collections.defaultdict(list)
for (i, num) in enumerate(a):
	lookup[num].append(i)
res = 0
pre = 0
t1 = []
for i in range(n, 0, -1):
	t1.append(min(lookup[i]))
t1 = t1[::-1]
pre = 0
for i in t1:
	res += abs(pre - i)
	pre = i
t2 = []
for i in range(n, 0, -1):
	t2.append(max(lookup[i]))
t2 = t2[::-1]
pre = 0
for i in t2:
	res += abs(pre - i)
	pre = i
print(res)


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


n = int(input())
l = list(map(int, input().split()))
lst = [(l[i], i) for i in range(len(l))]
lst = sorted(lst, key=lambda x: x[0])
dist1 = dist2 = 0
p1 = p2 = 0
for i in range(len(lst))[::2]:
	dist1 += abs(lst[i][1] - p1)
	dist2 += abs(lst[i + 1][1] - p2)
	p1 = lst[i][1]
	p2 = lst[i + 1][1]
print(dist1 + dist2)


import math
n = int(input())
a = list(map(int, input().split()))
p = [[] for i in range(2 * n)]
for i in range(2 * n):
	p[a[i] - 1].append(i)
i = 0
j = 0
nb = -1
ans = 0
while nb < n - 1:
	c = abs(i - p[nb + 1][0]) + abs(j - p[nb + 1][1])
	d = abs(i - p[nb + 1][1]) + abs(j - p[nb + 1][0])
	if c < d:
		ans += c
		i = p[nb + 1][0]
		j = p[nb + 1][1]
	else:
		ans += d
		i = p[nb + 1][1]
		j = p[nb + 1][0]
	nb += 1
print(ans)


n = int(input())
l = list(map(int, input().split()))
d = {}
s1 = set()
for i in range(len(l)):
	if l[i] not in s1:
		d[l[i]] = [0, 0]
		d[l[i]][0] = i + 1
		s1.add(l[i])
	else:
		d[l[i]][1] = i + 1
res = 0
x = 1
y = 1
for i in range(1, n + 1):
	res += abs(d[i][0] - x) + abs(d[i][1] - y)
	x = d[i][0]
	y = d[i][1]
print(res)


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
s = 0
prev1 = 0
prev2 = 0
for i in range(1, n + 1):
	cur1 = coords[str(i) + '_1']
	cur2 = coords[str(i) + '_2']
	d1 = abs(cur1 - prev1) + abs(cur2 - prev2)
	d2 = abs(cur1 - prev2) + abs(cur2 - prev1)
	s += min(d1, d2)
	prev1 = cur1
	prev2 = cur2
print(s)


n = int(input())
a = list(map(int, input().split()))
l = [i for i in range(2 * n)]
dp = list(zip(a, l))
dp.sort(key=lambda x: x[0])
x = []
y = []
for i in range(0, 2 * n - 1, 2):
	x.append(dp[i][1])
	y.append(dp[i + 1][1])
r1 = x[0] + y[0]
for i in range(1, n):
	r1 += min(abs(x[i] - x[i - 1]) + abs(y[i] - y[i - 1]), abs(y[i] - x[i - 1]) + abs(x[i] - y[i - 1]))
print(r1)


import math
n = int(input())
a = [int(i) for i in input().split(' ')]
dis = 0
location = [[] for x in range(n)]
for i in range(n * 2):
	location[a[i] - 1].append(i)
s = 0
d = 0
for i in range(n):
	loc = location[i]
	p1 = abs(loc[0] - s) + abs(loc[1] - d)
	p2 = abs(loc[0] - d) + abs(loc[1] - s)
	if p1 < p2:
		dis += p1
		s = loc[0]
		d = loc[1]
	else:
		dis += p2
		s = loc[0]
		d = loc[1]
print(dis)


import sys

def get_line():
	return list(map(int, sys.stdin.readline().strip().split()))

def in1():
	return int(input())
n = in1()
a = get_line()
d = {}
for i in range(2 * n):
	if a[i] not in d.keys():
		d[a[i]] = [i + 1]
	else:
		t1 = d[a[i]]
		t1.append(i + 1)
		d[a[i]] = t1
b = sorted(d.items())
c = 0
for i in range(len(b)):
	if i == 0:
		c += b[i][1][0] - 1
		c += b[i][1][1] - 1
	else:
		t1 = abs(b[i - 1][1][0] - b[i][1][0]) + abs(b[i - 1][1][1] - b[i][1][1])
		t2 = abs(b[i - 1][1][0] - b[i][1][1]) + abs(b[i - 1][1][1] - b[i][1][0])
		c += min(t1, t2)
print(c)


n = int(input())
a = list(map(int, input().split()))
d = {}
for i in range(1, n + 1):
	d[i] = []
for i in range(len(a)):
	d[a[i]].append(i)
for key in d:
	d[key] = sorted(d[key])
k = 0
z = 0
for i in range(1, n):
	k += abs(d[i][0] - d[i + 1][0])
for i in range(1, n):
	z += abs(d[i][1] - d[i + 1][1])
p = d[1][0]
q = d[1][1]
print(k + z + p + q)


from collections import defaultdict
n = int(input())
arr = list(map(int, input().split()))
dp = [[0] * 2 for i in range(2 * n + 1)]
pos_d = defaultdict(list)
for i in range(2 * n):
	el = arr[i]
	pos_d[el].append(i)
(pos_a, pos_b) = (0, 0)
dp[1] = [sum(pos_d[1]), sum(pos_d[1])]
for i in range(1, n):
	dp[i + 1][0] = min(dp[i][0] + abs(pos_d[i + 1][0] - pos_d[i][0]) + abs(pos_d[i + 1][1] - pos_d[i][1]), dp[i][1] + abs(pos_d[i + 1][0] - pos_d[i][1]) + abs(pos_d[i + 1][1] - pos_d[i][0]))
	dp[i + 1][1] = min(dp[i][0] + abs(pos_d[i + 1][1] - pos_d[i][0]) + abs(pos_d[i + 1][0] - pos_d[i][1]), dp[i][1] + abs(pos_d[i + 1][1] - pos_d[i][1]) + abs(pos_d[i + 1][0] - pos_d[i][0]))
print(min(dp[n]))


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()))
k = []
for j in range(n):
	k.append([])
for i in range(2 * n):
	k[a[i] - 1].append(i)
ans = k[0][0] + k[0][1]
for i in range(n - 1):
	ans += abs(k[i][0] - k[i + 1][0]) + abs(k[i][1] - k[i + 1][1])
print(ans)


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


n = int(input())
a = [[] for i in range(n)]
b = [int(i) for i in input().split()]
for i in range(2 * n):
	a[b[i] - 1].append(i)
ans = 0
sash = 0
dim = 0
for i in range(len(a)):
	ans += abs(sash - a[i][0]) + abs(dim - a[i][1])
	sash = a[i][0]
	dim = a[i][1]
print(ans)


import sys
import math
import copy
import heapq
import bisect
import string
import functools
import itertools
import collections
n = int(sys.stdin.readline())
l = list(map(int, sys.stdin.readline().strip().split()))
(i, ans, d) = (0, 0, dict.fromkeys(range(1, n + 1, 1), tuple([])))
while i < 2 * n:
	d[l[i]] = d[l[i]] + tuple([i])
	i = i + 1
(i, ans) = (1, ans + d[1][0] + d[1][1])
while i < n:
	if abs(d[i][0] - d[i + 1][0]) + abs(d[i][1] - d[i + 1][1]) <= abs(d[i][0] - d[i + 1][1]) + abs(d[i][1] - d[i + 1][0]):
		ans = ans + abs(d[i][0] - d[i + 1][0]) + abs(d[i][1] - d[i + 1][1])
	else:
		ans = ans + abs(d[i][0] - d[i + 1][1]) + abs(d[i][1] - d[i + 1][0])
	i = i + 1
sys.stdout.write(str(ans))


n = int(input())
cl = list(map(int, input().split()))
pos = [[0 for i in range(2)] for i in range(n)]
pl = [0 for i in range(n)]
for i in range(2 * n):
	if pl[cl[i] - 1] == 0:
		pos[cl[i] - 1][0] = i
		pl[cl[i] - 1] = 1
	else:
		pos[cl[i] - 1][1] = i
pos1 = 0
pos2 = 0
res = 0
for i in range(n):
	d1 = abs(pos1 - pos[i][0])
	d2 = abs(pos2 - pos[i][1])
	w1 = abs(pos1 - pos[i][1])
	w2 = abs(pos2 - pos[i][0])
	mn = min(d1 + d2, w1 + w2)
	if d1 + d2 == mn:
		pos1 = pos[i][0]
		pos2 = pos[i][1]
	else:
		pos1 = pos[i][1]
		pos2 = pos[i][0]
	res += mn
print(res)


n = int(input())
a = list(map(int, input().split()))
d = dict()
for i in range(2 * n):
	d[a[i]] = d.get(a[i], [])
	d[a[i]].append(i + 1)
s = -1
e = -1
ls = 0
le = 0
for i in range(1, n + 1):
	if s + d[i][0] + (e + d[i][1]) >= s + d[i][1] + (e + d[i][0]):
		s += abs(d[i][1] - ls)
		e += abs(d[i][0] - le)
		ls = d[i][1]
		le = d[i][0]
	else:
		s += abs(d[i][0] - ls)
		e += abs(d[i][1] - le)
		ls = d[i][0]
		le = d[i][1]
print(e + s)


import math
n = int(input())
a = [int(x) for x in input().split()]
uno = list()
for i in range(n + 1):
	uno.append(None)
dos = list()
for i in range(n + 1):
	dos.append(None)
for i in range(len(a)):
	if uno[a[i]] == None:
		uno[a[i]] = i + 1
	elif uno[a[i]] > i:
		dos[a[i]] = uno[a[i]]
		uno[a[i]] = i + 1
	else:
		dos[a[i]] = i + 1
uno[0] = 1
dos[0] = 1
suma = 0
for i in range(len(uno) - 1):
	suma += int(math.fabs(uno[i] - uno[i + 1]))
for i in range(len(dos) - 1):
	suma += int(math.fabs(dos[i] - dos[i + 1]))
print(suma)


tiers = int(input())
street = input().split()
for (i, j) in enumerate(street):
	street[i] = int(j)
myList = []
for i in range(int(len(street) / 2)):
	myList.append([])
for (i, j) in enumerate(street):
	myList[j - 1].append(i)
total = myList[0][0] + myList[0][1]
for i in range(tiers - 1):
	total += min((abs(myList[i][0] - myList[i + 1][0]) + abs(myList[i][1] - myList[i + 1][1]), abs(myList[i][0] - myList[i + 1][1]) + abs(myList[i][1] - myList[i + 1][0])))
print(total)


n = int(input())
a = list(map(int, input().split()))
dist = [[] for i in range(n)]
for i in range(2 * n):
	dist[a[i] - 1].append(i)
tot = 0
for i in range(n):
	if i == 0:
		tot += sum(dist[i])
		continue
	tot += abs(dist[i - 1][0] - dist[i][0]) + abs(dist[i - 1][1] - dist[i][1])
print(tot)


import sys

def dist(a, b):
	x1 = a // 2
	x2 = b // 2
	y1 = a % 2
	y2 = b % 2
	d = abs(x1 - x2) + abs(y1 - y2)
	return d
n = int(sys.stdin.readline())
a = list(map(int, sys.stdin.readline().split()))
locations = [[] for i in range(n)]
for i in range(2 * n):
	locations[a[i] - 1].append(i)
ans = 0
cur_loc = [0, 0]
for i in range(n):
	a = abs(cur_loc[0] - locations[i][0]) + abs(cur_loc[1] - locations[i][1])
	b = abs(cur_loc[0] - locations[i][1]) + abs(cur_loc[1] - locations[i][0])
	ans += min(a, b)
	cur_loc = locations[i]
print(ans)


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)


from sys import stdin, stdout

def getKey(item):
	return item[0]

def inp():
	return int(stdin.readline())

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

def linp():
	return list(minp())

def main():
	n = inp()
	l = linp()
	f1 = [-1] * 1000000
	f2 = [-1] * 1000000
	i = 0
	while i < 2 * n:
		if f1[l[i]] == -1:
			f1[l[i]] = i
		else:
			f2[l[i]] = i
		i += 1
	dist = f1[1] + f2[1]
	for i in range(1, n):
		d = f1[i] - f1[i + 1]
		if d < 0:
			d *= -1
		dist += d
		d = f2[i] - f2[i + 1]
		if d < 0:
			d *= -1
		dist += d
	print(dist)
main()


n = int(input())
a = [int(s) for s in input().split()]
b = []
for i in range(2 * n):
	b.append((a[i], i))
b.sort()
(d1, l1) = (0, 0)
(d2, l2) = (0, 0)
for i in range(2 * n):
	if i % 2 != 0:
		d1 += abs(b[i][1] - l1)
		l1 = b[i][1]
	else:
		d2 += abs(b[i][1] - l2)
		l2 = b[i][1]
print(d2 + d1)


n = int(input())
A = list(map(int, input().split()))
A = [a - 1 for a in A]
C = [[] for i in range(n)]
for (i, a) in enumerate(A):
	C[a].append(i)
from collections import defaultdict
INF = 10 ** 18
dp = defaultdict(lambda : INF)
dp[0, 0] = 0
for i in range(n):
	nx = defaultdict(lambda : INF)
	for ((s, d), v) in dp.items():
		ns = C[i][0]
		nd = C[i][1]
		nv = v + abs(ns - s) + abs(nd - d)
		nx[ns, nd] = min(nx[ns, nd], nv)
		ns = C[i][1]
		nd = C[i][0]
		nv = v + abs(ns - s) + abs(nd - d)
		nx[ns, nd] = min(nx[ns, nd], nv)
	dp = nx
print(min(dp.values()))


n = int(input())
a = [int(t) for t in input().split(' ')]
index = [[] for _ in range(n)]
for i in range(2 * n):
	index[a[i] - 1].append(i)
	index[a[i] - 1].sort()
INF = 10 ** 8
dp = [[INF, INF] for _ in range(n)]
dp[0][0] = index[0][0] + index[0][1]
dp[0][1] = index[0][1] + index[0][1]
for i in range(1, n):
	dp[i][0] = min(dp[i - 1][0] + abs(index[i - 1][0] - index[i][0]) + abs(index[i - 1][1] - index[i][1]), dp[i - 1][1] + abs(index[i - 1][1] - index[i][0]) + abs(index[i - 1][0] - index[i][1]))
	dp[i][1] = min(dp[i - 1][0] + abs(index[i - 1][0] - index[i][1]) + abs(index[i - 1][1] - index[i][0]), dp[i - 1][1] + abs(index[i - 1][1] - index[i][1]) + abs(index[i - 1][0] - index[i][0]))
print(min(*dp[n - 1]))


import math
from collections import deque, defaultdict
from sys import stdin, stdout
input = stdin.readline
listin = lambda : list(map(int, input().split()))
mapin = lambda : map(int, input().split())
n = int(input())
a = listin()
first = [0] * (n + 1)
second = [0] * (n + 1)
visited = [False] * (n + 1)
for i in range(2 * n):
	if not visited[a[i]]:
		first[a[i]] = i
		visited[a[i]] = True
	else:
		second[a[i]] = i
ans = 0
for i in range(1, n + 1):
	ans += abs(second[i] - second[i - 1])
	ans += abs(first[i] - first[i - 1])
print(ans)


class Pair:

	def __init__(self, x, y):
		self.x = x
		self.y = y
fileReader = None

def getInt():
	if fileReader is None:
		return int(input())
	else:
		return int(fileReader.readline())

def getList():
	if fileReader is None:
		return list(map(int, input().split(' ')))
	else:
		return list(map(int, fileReader.readline().split(' ')))

def getString():
	if fileReader is None:
		return input()
	else:
		return fileReader.readline()
n = getInt()
data = getList()
ans = []
for i in range(len(data)):
	ans.append([data[i], i])
ans.sort(key=lambda x: -x[0])
(x, y, c) = (0, 0, 0)
while len(ans) != 0:
	f1 = ans.pop()[1]
	f2 = ans.pop()[1]
	if abs(f1 - x) < f1 - y:
		c += abs(f1 - x)
		c += abs(f2 - y)
		x = f1
		y = f2
	else:
		c += abs(f2 - x)
		c += abs(f1 - y)
		x = f2
		y = f1
print(c)
if fileReader is not None:
	fileReader.close()


n = int(input())
l = list(map(int, input().split()))
lPosition = []
for i in range(len(l)):
	lPosition.append([l[i], i])
lPosition = sorted(lPosition)
firstPlace = 0
secondPlace = 0
res = 0
for i in range(0, len(lPosition), 2):
	res += abs(firstPlace - lPosition[i][1])
	firstPlace = lPosition[i][1]
	res += abs(secondPlace - lPosition[i + 1][1])
	secondPlace = lPosition[i + 1][1]
print(res)


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()


amount = int(input())
array = [int(s) for s in input().split()]
idx = [[] for i in range(amount)]
for i in range(len(array)):
	idx[array[i] - 1].append(i)
ans = sum(idx[0])
for i in range(len(idx) - 1):
	if abs(idx[i][0] - idx[i + 1][0]) + abs(idx[i][1] - idx[i + 1][1]) < abs(idx[i][0] - idx[i + 1][1]) + abs(idx[i][1] - idx[i + 1][0]):
		ans += abs(idx[i][0] - idx[i + 1][0]) + abs(idx[i][1] - idx[i + 1][1])
	else:
		ans += abs(idx[i][0] - idx[i + 1][1]) + abs(idx[i][1] - idx[i + 1][0])
print(ans)


n = int(input())
d = [[] for _ in range(n)]
d.insert(0, [0, 0])
for (i, v) in enumerate(map(int, input().split())):
	d[v].append(i)
print(sum(map(lambda x, y: min(abs(x[0] - y[0]) + abs(x[1] - y[1]), abs(x[0] - y[1]) + abs(x[1] - y[0])), d[1:], d)))


n = int(input())
a = list(map(int, input().split()))
if n == 1:
	print(1)
	exit()
h = {}
for i in range(len(a)):
	if a[i] in h:
		h[a[i]].append(i)
	else:
		h[a[i]] = [i]
closer = {}
for i in range(1, n):
	closer[i] = [min(h[i + 1]), max(h[i + 1])]
s = a.index(1)
s += abs(closer[1][0] - s)
carry = closer[1][0]
del closer[1][0]
for i in range(2, n):
	s += abs(closer[i][0] - carry)
	carry = closer[i][0]
	del closer[i][0]
d = 2 * n - a[::-1].index(1) - 1
d += abs(closer[1][0] - d)
carry = closer[1][0]
del closer[1][0]
for i in range(2, n):
	d += abs(closer[i][0] - carry)
	carry = closer[i][0]
	del closer[i][0]
print(d + s)


import sys
lines = []
for line in sys.stdin:
	lines.append(line)
shops = [int(coord) for coord in lines[1].split()]
indexes = [-1] * len(shops)
for (index, shop) in enumerate(shops):
	cur = (shop - 1) * 2
	if indexes[cur] == -1:
		indexes[cur] = index
	else:
		indexes[cur + 1] = index
sum = indexes[0] + indexes[1]
for i in range(len(indexes) // 2 - 1):
	sum += abs(indexes[2 * (i + 1)] - indexes[2 * i]) + abs(indexes[2 * (i + 1) + 1] - indexes[2 * i + 1])
print(sum)


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


n = int(input())
A = list(map(int, input().split()))
S = [[] for i in range(n + 1)]
for i in range(2 * n):
	S[A[i]].append(i)
S[0] = [0, 0]
ANS = 0
for i in range(1, n + 1):
	A = abs(S[i][0] - S[i - 1][0]) + abs(S[i][1] - S[i - 1][1])
	B = abs(S[i][1] - S[i - 1][0]) + abs(S[i][0] - S[i - 1][1])
	ANS += min(A, B)
print(ANS)


n = int(input())
a = [int(i) for i in input().split()]
pos = []
for (i, j) in enumerate(a):
	pos.append((j, i))
pos = sorted(pos)
ans = pos[0][1] + pos[1][1]
for i in range(2 * n - 2):
	ans += abs(pos[i][1] - pos[i + 2][1])
print(ans)


n = int(input())
a = list(map(int, input().split()))
d1 = [-1] * n
d2 = [-1] * n
for i in range(2 * n):
	if d1[a[i] - 1] != -1:
		d2[a[i] - 1] = i
	else:
		d1[a[i] - 1] = i
s = d1[0] + d2[0]
for i in range(n - 1):
	s += min(abs(d2[i] - d1[i + 1]) + abs(d1[i] - d2[i + 1]), abs(d2[i] - d2[i + 1]) + abs(d1[i] - d1[i + 1]))
print(s)


n = int(input())
arr = list(map(int, input().split()))
ans = 0
(ind1, ind2) = (0, 0)
nexts_dict = {}
for i in range(len(arr)):
	item = arr[i]
	if item in nexts_dict:
		nexts_dict[item].append(i)
	else:
		nexts_dict[item] = [i]
for i in range(1, n + 1):
	nexts = nexts_dict[i]
	option1 = abs(ind1 - nexts[0]) + abs(ind2 - nexts[1])
	option2 = abs(ind2 - nexts[0]) + abs(ind1 - nexts[1])
	if option1 <= option2:
		ans += option1
		ind1 = nexts[0]
		ind2 = nexts[1]
	else:
		ans += option2
		ind1 = nexts[1]
		ind2 = nexts[0]
print(ans)


def compute(n, a):
	loc = sorted(list(enumerate(a)), key=lambda x: (x[1], x[0]))
	loc = list(map(lambda x: x[0], loc))
	cur = (0, 0)
	ret = 0
	for x in range(0, n * 2, 2):
		c = abs(cur[0] - loc[x]) + abs(cur[1] - loc[x + 1])
		d = abs(cur[1] - loc[x]) + abs(cur[0] - loc[x + 1])
		ret += min(c, d)
		cur = (loc[x], loc[x + 1])
	return ret
from sys import stdin
[n] = list(map(int, stdin.readline().split()))
a = list(map(int, stdin.readline().split()))
print(compute(n, a))


n = int(input())
houses = tuple([int(x) for x in input().split()])
firstOccurence = {0: 0}
secondOccurence = {0: 0}
dist = 0
for i in range(1, n + 1):
	firstOccurence.setdefault(i, -1)
for i in range(2 * n):
	number = houses[i]
	if firstOccurence[number] != -1:
		secondOccurence.setdefault(number, i)
	else:
		firstOccurence[number] = i
for i in range(1, n + 1):
	dist += abs(firstOccurence[i] - firstOccurence[i - 1]) + abs(secondOccurence[i] - secondOccurence[i - 1])
print(dist)


import sys
input = sys.stdin.readline
n = int(input())
positions = {}
for i in range(1, n + 1):
	positions[i] = []
a = list(map(int, input().split()))
for i in range(n * 2):
	positions[a[i]].append(i)
ans = positions[1][0] + positions[1][1]
for i in range(1, n):
	ans += abs(positions[i + 1][0] - positions[i][0])
	ans += abs(positions[i + 1][1] - positions[i][1])
print(ans)


n = int(input())
s = [int(i) for i in input().split(' ')]
mas = []
for i in range(n):
	mas.append([])
for i in range(len(s)):
	mas[s[i] - 1].append(i)
t = mas[0][0] + mas[0][1]
for i in range(1, len(mas)):
	t += abs(mas[i][0] - mas[i - 1][0])
	t += abs(mas[i][1] - mas[i - 1][1])
print(t)


a = [() for _ in [0] * int(input())]
i = 0
for x in map(int, input().split()):
	a[x - 1] += (i,)
	i += 1
print(sum((abs(y - x) for t in zip(*a) for (x, y) in zip((0,) + t, t))))


N = int(input())
A = list(map(int, input().split()))
left = {}
right = {}
i = 1
for a in A:
	if a in left.keys():
		right[a] = i
	else:
		left[a] = i
	i += 1
r = 0
sasha = 1
dima = 1
for i in range(N):
	r += abs(left[i + 1] - sasha) + abs(right[i + 1] - dima)
	sasha = left[i + 1]
	dima = right[i + 1]
print(r)


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)
threading.stack_size(2 ** 27)
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, 1000000000.0)
max_operation = Operation('max', max, max_multiple, -1000000000.0)

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):
	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):
	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 = []
entry_finder = {}
REMOVED = '<removed-task>'

def add_task(task, priority=0):
	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):
	entry = entry_finder.pop(task)
	entry[-1] = REMOVED

def pop_task():
	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):
	fn = lambda x: li[x] - x // i
	x = -1
	b = len(li)
	while b >= 1:
		while b + x < len(li) and fn(b + x) > 0:
			x += b
		b = b // 2
	return x
TestCases = False
testingMode = False
fac_warmup_size = 10 ** 5 + 100
optimiseForReccursion = True

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)
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()


import sys

class BTwoCakes:

	def solve(self):
		n = int(input())
		a = [int(_) for _ in input().split()]
		pos = [[] for _ in range(n + 1)]
		for i in range(2 * n):
			pos[a[i]] += [i]
		ans = float('inf')
		for p in range(2):
			cur1 = pos[1][p]
			cur2 = pos[1][1 - p]
			cur_ans = cur1 + cur2
			for i in range(2, n + 1):
				if abs(pos[i][0] - cur1) + abs(pos[i][1] - cur2) <= abs(pos[i][0] - cur2) + abs(pos[i][1] - cur1):
					cur_ans += abs(pos[i][0] - cur1)
					cur_ans += abs(pos[i][1] - cur2)
					(cur1, cur2) = pos[i]
				else:
					cur_ans += abs(pos[i][1] - cur1)
					cur_ans += abs(pos[i][0] - cur2)
					(cur2, cur1) = pos[i]
			ans = min(ans, cur_ans)
		print(ans)
solver = BTwoCakes()
input = sys.stdin.readline
solver.solve()


n = int(input())
x = input().split()
x = list(map(int, x))
ss = [x.index(1)]
dd = [x[x.index(1) + 1:].index(1) + x.index(1) + 1]
lasts = ss[0]
lastd = dd[0]
summ = lasts + lastd
arr = [[] for i in range(n)]
for i in range(2 * n):
	arr[x[i] - 1].append(i)
for i in range(n):
	first = arr[i][0]
	second = arr[i][1]
	a = abs(lasts - first)
	b = abs(lastd - second)
	c = abs(lasts - second)
	d = abs(lastd - first)
	lastd = first
	lasts = second
	summ += min(a + b, c + d)
print(summ)


n = int(input())
list = [int(i) for i in input().split()]
r = []
for i in range(2 * n):
	r.append([list[i], i])
r.sort()
tol = r[0][1] + r[1][1]
for i in range(2 * n - 2):
	tol += abs(r[i + 2][1] - r[i][1])
print(tol)


from collections import defaultdict
n = int(input())
d = defaultdict(list)
d[0] = [0, 0]
for (i, a) in enumerate(map(int, input().split())):
	d[a].append(i)
print(sum((abs(d[i][j] - d[i + 1][j]) for i in range(n) for j in range(2))))


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)


from collections import defaultdict as df
n = int(input())
a = [int(e) for e in input().split()]
m = df(list)
l = []
x = y = 1
p = 0
for i in range(2 * n):
	m[a[i]].append(i + 1)
for i in range(1, n + 1):
	s = abs(x - m[i][0]) + abs(y - m[i][1])
	t = abs(x - m[i][1]) + abs(y - m[i][0])
	if s > t:
		p += t
		x = m[i][1]
		y = m[i][0]
	else:
		p += s
		x = m[i][0]
		y = m[i][1]
print(p)


n = int(input())
(i, a) = (0, [])
for x in input().split():
	a.append([int(x), i])
	i += 1
a.sort()
(x1, x2, i, ans) = (0, 0, 0, 0)
for _ in range(n):
	r1 = abs(a[i][1] - x1) + abs(a[i + 1][1] - x2)
	r2 = abs(a[i][1] - x2) + abs(a[i + 1][1] - x1)
	if r1 > r2:
		ans += r2
		(x1, x2) = (a[i + 1][1], a[i][1])
	else:
		ans += r1
		(x2, x1) = (a[i + 1][1], a[i][1])
	i += 2
print(ans)


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)


import math
n = int(input())
arr = list(map(int, input().split()))
arr2D = [[arr[i], i] for i in range(len(arr))]
arr2D = sorted(arr2D, key=lambda x: (x[0], x[1]))
output = 0
i = 0
j = 0
for k in range(0, 2 * n, 2):
	x = abs(arr2D[k][1] - i)
	y = abs(arr2D[k + 1][1] - j)
	output += x + y
	i = arr2D[k][1]
	j = arr2D[k + 1][1]
print(output)


n = int(input().strip())
a = list(map(int, input().strip().split()))
d = {}
for i in range(2 * n):
	if a[i] in d.keys():
		d[a[i]] += [i]
	else:
		d[a[i]] = [i]
result = 0
for i in range(1, n):
	a1 = d[i]
	a2 = d[i + 1]
	result += min(abs(a1[0] - a2[0]) + abs(a1[1] - a2[1]), abs(a1[0] - a2[1]) + abs(a1[1] - a2[0]))
result += d[1][0] + d[1][1]
print(result)


n = int(input())
a = list(map(int, input().split()))
s = {}
for q in range(len(a)):
	s[a[q]] = s.get(a[q], []) + [q]
ans = x = y = 0
for q in range(1, n + 1):
	if abs(x - s[q][0]) + abs(y - s[q][1]) > abs(x - s[q][1]) + abs(y - s[q][0]):
		ans += abs(x - s[q][1]) + abs(y - s[q][0])
	else:
		ans += abs(x - s[q][0]) + abs(y - s[q][1])
	(x, y) = (s[q][0], s[q][1])
print(ans)


import sys
t = int(sys.stdin.readline())
l = list(map(int, sys.stdin.readline().split()))
list1 = []
for i in range(2 * t):
	list1.append([l[i], i])
list1 = [[0, 0], [0, 0]] + list1
list1.sort()
summ = 0
for i in range(2 * t):
	summ += abs(list1[i][1] - list1[i + 2][1])
print(summ)


n = int(input())
arr = list(map(int, input().split()))
matrix = [[-1] * 0 for i in range(n)]
for (i, n) in enumerate(arr):
	matrix[n - 1].append(i)
(di, si) = (0, 0)
dist = 0
for i in matrix:
	dist = dist + abs(i[0] - si)
	si = i[0]
	dist = dist + abs(i[1] - di)
	di = i[1]
print(dist)


n = int(input())
a = list(map(int, input().split()))
counts = [0 for i in range(len(a))]
used = set()
for i in range(len(a)):
	if a[i] in used:
		counts[i] = 2
		continue
	used.add(a[i])
	counts[i] = 1
fst = [(v, idx) for (idx, (v, num)) in enumerate(zip(a, counts)) if num == 1]
snd = [(v, idx) for (idx, (v, num)) in enumerate(zip(a, counts)) if num == 2]
total = 0
fst = sorted(fst, key=lambda x: x[0])
total += fst[0][1]
for i in range(1, len(fst)):
	total += abs(fst[i][1] - fst[i - 1][1])
snd = sorted(snd, key=lambda x: x[0])
total += snd[0][1]
for i in range(1, len(snd)):
	total += abs(snd[i][1] - snd[i - 1][1])
print(total)


n = int(input())
d = {}
d[0] = [0, 0]
for i in range(1, n + 1):
	d[i] = []
l = [int(x) for x in input().split()]
for i in range(len(l)):
	d[l[i]].append(i)
mileage = 0
for i in range(1, n + 1):
	mileage += min(abs(d[i][0] - d[i - 1][0]) + abs(d[i][1] - d[i - 1][1]), abs(d[i][0] - d[i - 1][1]) + abs(d[i][1] - d[i - 1][0]))
print(mileage)


from sys import stdin
n = int(stdin.readline())
l = [int(x) for x in stdin.readline().rstrip().split()]
d = {v + 1: [] for v in range(n)}
for (i, v) in enumerate(l):
	d[v].append(i)
c = 0
currs = 0
currd = 0
for i in range(n):
	next1 = d[i + 1][0]
	next2 = d[i + 1][1]
	d1 = abs(next1 - currs)
	d2 = abs(next1 - currd)
	d3 = abs(next2 - currs)
	d4 = abs(next2 - currd)
	if d1 + d4 < d2 + d3:
		currs = next1
		currd = next2
		c += d1 + d4
	else:
		currs = next2
		currd = next1
		c += d2 + d3
print(c)


n = int(input())
arr = list(map(int, input().split()))
pos = [0] * (n + 1)
for i in range(n + 1):
	pos[i] = []
pos[0] = [0, 0]
for i in range(2 * n):
	pos[arr[i]].append(i)
ans = 0
for i in range(n):
	ans += abs(pos[i + 1][0] - pos[i][0])
	ans += abs(pos[i + 1][1] - pos[i][1])
print(ans)


from sys import stdin, stdout
from itertools import combinations
from collections import defaultdict
import math

def listIn():
	return list(map(int, stdin.readline().strip().split()))

def stringListIn():
	return [x for x in stdin.readline().split()]

def intIn():
	return int(stdin.readline())

def stringIn():
	return stdin.readline().strip()
n = intIn()
a = listIn()
b = list(range(1, n + 1))
ans = 0
di = {}
for i in range(2 * n):
	if a[i] not in di:
		di[a[i]] = []
	di[a[i]].append(i)
for i in range(n):
	if b[i] == 1:
		ans += sum(di[b[i]])
	else:
		l1 = di[b[i]]
		l2 = di[b[i - 1]]
		(m1, m2) = (abs(l2[0] - l1[0]), abs(l2[0] - l1[1]))
		(m3, m4) = (abs(l2[1] - l1[0]), abs(l2[1] - l1[1]))
		(m5, m6) = (min(m1, m2), min(m3, m4))
		if m5 == m1:
			m7 = m5 + m4
		else:
			m7 = m5 + m3
		if m6 == m3:
			m8 = m6 + m2
		else:
			m8 = m6 + m1
		ans += min(m7, m8)
print(ans)


n = int(input())
l = list(map(int, input().split()))
d = {}
s1 = set()
for i in range(len(l)):
	if l[i] not in s1:
		d[l[i]] = [0, 0]
		d[l[i]][0] = i + 1
		s1.add(l[i])
	else:
		d[l[i]][1] = i + 1
s = 0
u = 1
v = 1
for j in range(1, n + 1):
	s += abs(d[j][0] - u) + abs(d[j][1] - v)
	u = d[j][0]
	v = d[j][1]
print(s)


import sys
sys.setrecursionlimit(10 ** 5 + 1)
inf = int(10 ** 20)
max_val = inf
min_val = -inf
RW = lambda : sys.stdin.readline().strip()
RI = lambda : int(RW())
RMI = lambda : [int(x) for x in sys.stdin.readline().strip().split()]
RWI = lambda : [x for x in sys.stdin.readline().strip().split()]
nb_house = RI()
a = [[] for _ in range(nb_house)]
houses = RMI()
for (i, v) in enumerate(houses):
	a[v - 1] += (i,)
s = 0
(x, y) = (0, 0)
for (u, v) in a:
	s += min(abs(x - u) + abs(y - v), abs(x - v) + abs(y - u))
	(x, y) = (u, v)
print(s)


n = int(input())
m = list(map(int, input().split()))
pos = [[] for i in range(n)]
for (i, x) in enumerate(m):
	pos[x - 1].append(i)
(x1, y1) = (0, 0)
ans = 0
for (x, y) in pos:
	ans += min(abs(x1 - x) + abs(y1 - y), abs(x1 - y) + abs(y1 - x))
	(x1, y1) = (x, y)
print(ans)


(n, a, k, s0, m0, shag) = (int(input()), dict(), 0, 1, 1, 0)
for i in input().split():
	k += 1
	j = int(i)
	if j not in a:
		a[j] = [k]
	else:
		a[j].append(k)
for i in range(1, n + 1):
	(s1, s2, m1, m2) = (abs(a[i][0] - s0), abs(a[i][1] - s0), abs(a[i][0] - m0), abs(a[i][1] - m0))
	if s1 + m2 <= s2 + m1:
		(s0, m0) = (a[i][0], a[i][1])
		shag += s1 + m2
	else:
		(s0, m0) = (a[i][1], a[i][0])
		shag += s2 + m1
print(shag)


n = int(input())
a = list(map(int, input().split()))
locations = [[] for i in range(n)]
for (i, e) in enumerate(a):
	locations[e - 1].append(i)
(p0, p1) = (0, 0)
cnt = 0
for i in range(n):
	(l0, l1) = locations[i]
	v0 = abs(p0 - l0) + abs(p1 - l1)
	v1 = abs(p0 - l1) + abs(p1 - l0)
	if v0 < v1:
		p0 = l0
		p1 = l1
		cnt += v0
	else:
		p0 = l1
		p1 = l0
		cnt += v1
print(cnt)


import sys
input = sys.stdin.buffer.readline
n = int(input())
a = list(map(int, input().split()))
idx = [[] for i in range(n + 1)]
idx[0].append(0)
idx[0].append(0)
for i in range(2 * n):
	idx[a[i]].append(i)
res = 0
(b, c) = (0, 0)
for (d, e) in idx:
	res += min(abs(b - d) + abs(c - e), abs(b - e) + abs(c - d))
	(b, c) = (d, e)
print(res)


n = int(input())
houses = [[i, int(x)] for (i, x) in enumerate(input().split())]
dist = 0
sPos = 0
dPos = 0
houses = sorted(houses, key=lambda x: x[1])
for i in range(0, n * 2, 2):
	dist1 = abs(sPos - houses[i][0]) + abs(dPos - houses[i + 1][0])
	dist2 = abs(dPos - houses[i][0]) + abs(sPos - houses[i + 1][0])
	if dist1 < dist2:
		sPos = houses[i][0]
		dPos = houses[i + 1][0]
		dist += dist1
	else:
		sPos = houses[i + 1][0]
		dPos = houses[i][0]
		dist += dist2
print(dist)


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 readLine():
	a = input()
	return [int(i) for i in a.split(' ')]
n = readLine()[0]
a = readLine()
x = [None] * (n + 1)
y = [None] * (n + 1)
for (i, val) in enumerate(a):
	if x[val - 1] == None:
		x[val - 1] = i
	else:
		y[val - 1] = i
ans = x[0] + y[0]
for i in range(n - 1):
	ans += min(abs(x[i] - x[i + 1]) + abs(y[i] - y[i + 1]), abs(x[i] - y[i + 1]) + abs(y[i] - x[i + 1]))
print(ans)


n = int(input())
cakes = list(map(int, input().split()))
positions = [[] for i in range(n + 1)]
for i in range(2 * n):
	positions[cakes[i]].append(i)
res = 0
pos1 = 0
pos2 = 0
for i in range(1, n + 1):
	res += min(abs(pos1 - positions[i][0]) + abs(pos2 - positions[i][1]), abs(pos1 - positions[i][1]) + abs(pos2 - positions[i][0]))
	(pos1, pos2) = positions[i]
print(res)


n = int(input())
a = list(map(int, input().split()))
x = [[i, -1, -1] for i in range(n + 1)]
for i in range(2 * n):
	if x[a[i]][1] != -1:
		x[a[i]][2] = i
	else:
		x[a[i]][1] = i
pos1 = 0
pos2 = 0
dist = 0
for i in range(1, n + 1):
	if abs(x[i][1] - pos1) + abs(x[i][2] - pos2) < abs(x[i][1] - pos2) + abs(x[i][2] - pos1):
		dist += abs(x[i][1] - pos1) + abs(x[i][2] - pos2)
		pos1 = x[i][1]
		pos2 = x[i][2]
	else:
		dist += abs(x[i][1] - pos2) + abs(x[i][2] - pos1)
		pos1 = x[i][2]
		pos2 = x[i][1]
print(dist)


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


class tier:

	def __init__(self, a, b):
		self.val = a
		self.index = b

def cmp(t):
	return t.val
n = int(input())
t = []
a = list(map(int, input().split()))
for i in range(2 * n):
	t.append(tier(a[i], i))
t.sort(key=cmp)
ans = t[0].index + t[1].index
for i in range(0, 2 * n - 2, 2):
	ans += abs(t[i + 2].index - t[i].index)
for i in range(1, 2 * n - 1, 2):
	ans += abs(t[i + 2].index - t[i].index)
print(ans)


import sys

def cakes(lst):
	ref = {}
	d_dst = 0
	d_cur = 0
	s_dst = 0
	s_cur = 0
	for i in range(len(lst)):
		if lst[i] in ref.keys():
			ref[lst[i]].append(i)
		else:
			ref[lst[i]] = [i]
	for i in range(len(lst) // 2):
		i = i + 1
		zero_to_s = abs(ref[i][0] - s_cur)
		one_to_s = abs(ref[i][1] - s_cur)
		zero_to_d = abs(ref[i][0] - d_cur)
		one_to_d = abs(ref[i][1] - d_cur)
		if zero_to_d + one_to_s < zero_to_s + one_to_d:
			d_new = ref[i][0]
			s_new = ref[i][1]
		else:
			d_new = ref[i][1]
			s_new = ref[i][0]
		d_dst += abs(d_cur - d_new)
		s_dst += abs(s_cur - s_new)
		d_cur = d_new
		s_cur = s_new
	return d_dst + s_dst
first = True
for line in sys.stdin:
	if first:
		first = False
		continue
	l = line.strip().split(' ')
	l = [int(x) for x in l]
	s = cakes(l)
print(s)


import bisect
import decimal
from decimal import Decimal
import os
from collections import Counter
import bisect
from collections import defaultdict
import math
import random
import heapq
from math import sqrt
import sys
from functools import reduce, cmp_to_key
from collections import deque
import threading
from itertools import combinations
from io import BytesIO, IOBase
from itertools import accumulate
mod = 10 ** 9 + 7
decimal.getcontext().prec = 46

def primeFactors(n):
	prime = set()
	while n % 2 == 0:
		prime.add(2)
		n = n // 2
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			prime.add(i)
			n = n // i
	if n > 2:
		prime.add(n)
	return list(prime)

def getFactors(n):
	factors = []
	i = 1
	while i <= math.sqrt(n):
		if n % i == 0:
			if n // i == i:
				factors.append(i)
			else:
				factors.append(i)
				factors.append(n // i)
		i = i + 1
	return factors

def modefiedSieve():
	mx = 10 ** 7 + 1
	sieve = [-1] * mx
	for i in range(2, mx):
		if sieve[i] == -1:
			sieve[i] = i
			for j in range(i * i, mx, i):
				if sieve[j] == -1:
					sieve[j] = i
	return sieve

def SieveOfEratosthenes(n):
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	num = []
	for p in range(2, n + 1):
		if prime[p]:
			num.append(p)
	return num

def lcm(a, b):
	return a * b // math.gcd(a, b)

def sort_dict(key_value):
	return sorted(key_value.items(), key=lambda kv: (kv[1], kv[0]), reverse=True)

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

def num_input():
	return map(int, input().split())

def string_list():
	return list(input())

def decimalToBinary(n):
	return bin(n).replace('0b', '')

def binaryToDecimal(n):
	return int(n, 2)

def DFS(n, adj, s):
	visited = [False for i in range(n + 1)]
	stack = []
	stack.append(s)
	while len(stack):
		s = stack[-1]
		stack.pop()
		if not visited[s]:
			visited[s] = True
		for node in adj[s]:
			if not visited[node]:
				stack.append(node)

def maxSubArraySum(a, size):
	max_so_far = -sys.maxsize - 1
	max_ending_here = 0
	start = 0
	end = 0
	s = 0
	for i in range(0, size):
		max_ending_here += a[i]
		if max_so_far < max_ending_here:
			max_so_far = max_ending_here
			start = s
			end = i
		if max_ending_here < 0:
			max_ending_here = 0
			s = i + 1
	return (max_so_far, start, end)

def lis(arr):
	n = len(arr)
	lis = [1] * n
	for i in range(1, n):
		for j in range(0, i):
			if arr[i] >= arr[j] and lis[i] < lis[j] + 1:
				lis[i] = lis[j] + 1
	maximum = 0
	for i in range(n):
		maximum = max(maximum, lis[i])
	return maximum

def solve():
	n = int(input())
	arr = list_input()
	a = [[0, 0], [0, 0]]
	for i in range(2 * n):
		a.append([arr[i], i])
	a.sort()
	ans = 0
	for i in range(2 * n):
		ans += abs(a[i][1] - a[i + 2][1])
	print(ans)
t = 1
for _ in range(t):
	solve()


import sys
inf = float('inf')
mod = 1000000007

def get_array():
	return list(map(int, sys.stdin.readline().split()))

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

def input():
	return sys.stdin.readline()

def main():
	n = int(input())
	arr = get_array()
	d = {}
	for i in range(2 * n):
		if arr[i] not in d:
			d[arr[i]] = []
		d[arr[i]].append(i)
	new = {}
	for key in sorted(d):
		new[key] = d[key]
	(x, y) = (0, 0)
	(prev_x, prev_y) = (0, 0)
	for i in new:
		x += abs(new[i][0] - prev_x)
		prev_x = new[i][0]
		y += abs(new[i][1] - prev_y)
		prev_y = new[i][1]
	print(x + y)
main()


n = int(input())
l = list(map(int, input().split()))
fr = set()
sd = set()
l1 = []
l2 = []
for i in range(len(l)):
	if l[i] not in fr:
		l1.append([l[i], i])
		fr.add(l[i])
	elif l[i] not in sd:
		l2.append([l[i], i])
		sd.add(l[i])
l1.sort()
l2.sort()
s1 = l1[0][1]
s2 = l2[0][1]
for i in range(1, len(l1)):
	s1 += abs(l1[i][1] - l1[i - 1][1])
	s2 += abs(l2[i][1] - l2[i - 1][1])
print(s1 + s2)


n = int(input())
a = list(map(int, input().split()))
sa = 0
di = 0
dict = {}
for i in range(1, n + 1):
	dict[i] = []
for i in range(1, 2 * n + 1):
	dict[a[i - 1]].append(i - 1)
x = 0
y = 0
for i in range(1, n + 1):
	sa += abs(x - dict[i][0])
	di += abs(y - dict[i][1])
	x = dict[i][0]
	y = dict[i][1]
print(sa + di)


from sys import stdin, stdout
for _ in range(1):
	n = int(stdin.readline())
	a = list(map(int, stdin.readline().split()))
	l = []
	for i in range(2 * n):
		l += [[a[i], i]]
	l.sort()
	prev = ans = 0
	for i in range(0, 2 * n, 2):
		ans += abs(prev - l[i][1])
		prev = l[i][1]
	prev = 0
	for i in range(1, 2 * n, 2):
		ans += abs(prev - l[i][1])
		prev = l[i][1]
	print(ans)


from collections import deque
import heapq
import math
import bisect

def main():
	N = int(input())
	A = list(map(int, input().split()))
	G = [[] for i in range(N)]
	for i in range(2 * N):
		G[A[i] - 1].append(i)
	sy = di = 0
	ps = pd = 0
	for i in range(N):
		G[i].sort()
		sy += abs(ps - G[i][0])
		di += abs(pd - G[i][1])
		ps = G[i][0]
		pd = G[i][1]
	print(sy + di)
main()


n = int(input())
array = [int(s) for s in input().split(' ')]
locations = sorted(range(2 * n), key=lambda x: array[x])
place = (0, 0)
dist = 0
for i in range(n):
	l1 = locations[2 * i]
	l2 = locations[2 * i + 1]
	dist += min(abs(place[0] - l1) + abs(place[1] - l2), abs(place[0] - l2) + abs(place[1] - l1))
	place = (l1, l2)
print(dist)


def f(w):
	return w[0]

def f1(w):
	return w[1]
n = int(input())
a = [[int(e)] for e in input().split()]
for i in range(2 * n):
	a[i].append(i)
w = a[0]
a.sort(key=f1)
a.sort(key=f)
res = 0
w = 0
w1 = 0
for i in range(0, 2 * n, 2):
	q = abs(a[i][1] - w)
	q1 = abs(a[i][1] - w1)
	q2 = abs(a[i + 1][1] - w)
	q3 = abs(a[i + 1][1] - w1)
	if q + q3 < q1 + q2:
		w = a[i][1]
		w1 = a[i + 1][1]
		res += q + q3
	else:
		w = a[i + 1][1]
		w1 = a[i][1]
		res += q1 + q2
print(res)


from math import ceil
n = int(input())
A = list(map(int, input().split()))
(s, d) = ([-1 for i in range(n + 1)], [-1 for i in range(n + 1)])
dist = 0
for i in range(2 * n):
	if s[A[i]] == -1:
		s[A[i]] = i
		if A[i] == 1:
			dist += i
			if len(s) > 2 and s[2] != -1:
				dist += abs(i - s[2])
			continue
		if len(s) > 2 and A[i] == n and (s[n - 1] != -1):
			dist += abs(i - s[n - 1])
			continue
		if s[A[i] - 1] > -1:
			dist += abs(s[A[i] - 1] - s[A[i]])
		if A[i] != n and s[A[i] + 1] > -1:
			dist += abs(s[A[i] + 1] - s[A[i]])
	elif d[A[i]] == -1:
		d[A[i]] = i
		if A[i] == 1:
			dist += i
			if len(d) > 2 and d[2] != -1:
				dist += abs(i - d[2])
			continue
		if len(d) > 2 and A[i] == n and (d[n - 1] != -1):
			dist += abs(i - d[n - 1])
			continue
		if d[A[i] - 1] > -1:
			dist += abs(d[A[i] - 1] - d[A[i]])
		if A[i] != n and d[A[i] + 1] > -1:
			dist += abs(d[A[i] + 1] - d[A[i]])
print(dist)


n = int(input())
houses = list(map(int, input().strip().split(' ')))
i = list(range(2 * n))
h = sorted([[houses[j], i[j]] for j in range(2 * n)])
s = h[0][1] + h[1][1]
for k in range(n - 1):
	s += min(abs(h[2 * k][1] - h[2 * k + 2][1]) + abs(h[2 * k + 1][1] - h[2 * k + 3][1]), abs(h[2 * k][1] - h[2 * k + 3][1]) + abs(h[2 * k + 1][1] - h[2 * k + 2][1]))
print(s)


n = int(input())
ns = map(int, input().split())
dis = [(i, idx) for (idx, i) in enumerate(ns)]
del ns
dis.sort()
a = 0
b = 0
ans = 0
for i in range(0, n * 2, 2):
	(_, d1) = dis[i]
	(_, d2) = dis[i + 1]
	a_d1 = abs(d1 - a)
	b_d1 = abs(d1 - b)
	a_d2 = abs(d2 - a)
	b_d2 = abs(d2 - b)
	if a_d1 + b_d2 < a_d2 + b_d1:
		ans += a_d1
		ans += b_d2
		a = d1
		b = d2
	else:
		ans += a_d2
		ans += b_d1
		a = d2
		b = d1
print(ans)


from math import ceil

def arr_scan():
	return list(map(int, input().split(' ')))
n = arr_scan()[0]
arr = arr_scan()
mapi = [[] for _ in range(n + 1)]
for (idx, num) in enumerate(arr):
	mapi[num].append(idx)
(start1, start2) = mapi[1]
cost = start1 + start2
for i in range(2, n + 1):
	(c1, c2) = mapi[i]
	val1 = abs(start1 - c1) + abs(start2 - c2)
	val2 = abs(start1 - c2) + abs(start2 - c1)
	if val1 >= val2:
		cost += val2
		start1 = c1
		start2 = c2
	else:
		cost += val1
		start1 = c2
		start2 = c1
print(cost)


x = int(input(''))
y = list(map(int, input('').split()))
s = [[] for i in range(x + 1)]
for i in range(len(y)):
	s[y[i]].append(i)
a = abs(s[1][0]) + abs(s[1][1])
for i in range(1, x):
	a += min(abs(s[i][0] - s[i + 1][0]) + abs(s[i][1] - s[i + 1][1]), abs(s[i][0] - s[i + 1][1]) + abs(s[i][1] - s[i + 1][0]))
print(a)


from math import ceil
n = int(input())
idx = {}
num = list(map(int, input().split()))
for i in range(2 * n):
	elem = num[i]
	if elem in idx.keys():
		idx[elem] += [i]
	else:
		idx[elem] = [i]
ans = sum(idx[1])
for i in range(1, n):
	a = idx[i]
	b = idx[i + 1]
	ans += min(abs(a[0] - b[0]) + abs(a[1] - b[1]), abs(a[0] - b[1]) + abs(a[1] - b[0]))
print(ans)


def cake_problem():
	n = int(input())
	a = []
	for i in range(n + 1):
		a.append([-1, -1])
	l = input().split(' ')
	for i in range(len(l)):
		l[i] = int(l[i])
		b = l[i]
		if a[b - 1][0] == -1:
			a[b - 1][0] = i
		else:
			a[b - 1][1] = i
	(len1, len2) = (a[0][0], a[0][1])
	for i in range(1, n):
		len1 += abs(a[i][0] - a[i - 1][0])
		len2 += abs(a[i][1] - a[i - 1][1])
	print(len1 + len2)
	return
cake_problem()


n = int(input())
A = list(map(int, input().split()))
MS = {}
MD = {}
bil = set()
for i in range(2 * n):
	if A[i] in bil:
		MD[A[i]] = i
	else:
		MS[A[i]] = i
	bil.add(A[i])
nowms = 0
nowmd = 0
cnt = 0
for u in range(1, n + 1):
	cnt += abs(MS[u] - nowms)
	cnt += abs(MD[u] - nowmd)
	nowms = MS[u]
	nowmd = MD[u]
print(cnt)


n = int(input())
answer = 0
a = list(map(int, input().split()))
for i in range(2 * n):
	a[i] = (a[i], i)
a.sort()
answer = a[0][1] + a[1][1]
for i in range(2, len(a) - 1, 2):
	answer += abs(a[i - 2][1] - a[i][1]) + abs(a[i - 1][1] - a[i + 1][1])
print(answer)


import math
n = int(input())
c = 0
a = list(map(int, input().split()))
b = [[-1 for i in range(2)] for j in range(n + 1)]
b[0] = [0, 0]
for i in range(2 * n):
	if b[a[i]][0] == -1:
		b[a[i]][0] = i
	else:
		b[a[i]][1] = i
for i in range(n):
	c += min(abs(b[i + 1][0] - b[i][0]) + abs(b[i + 1][1] - b[i][1]), abs(b[i + 1][1] - b[i][0]) + abs(b[i + 1][0] - b[i][1]))
print(c)


n = int(input())
a = list(map(int, input().split()))
sa = [[] for i in range(n + 1)]
for (i, j) in enumerate(a):
	sa[j].append(i)
ans = 0
(pv1, pv2) = (0, 0)
ch = 0
for i in range(1, n + 1):
	ans += abs(pv1 - sa[i][0]) + abs(sa[i][1] - pv2)
	(pv1, pv2) = sa[i]
print(ans)


n = int(input())
a = [int(x) for x in input().split()]
m = [int(x) for x in range(len(a))]
d = tuple(zip(a, m))
d1 = sorted(d)
e = [d1[0][1]]
for i in range(2, len(d1), 2):
	e.append(abs(d1[i - 2][1] - d1[i][1]))
o = [d1[1][1]]
for j in range(3, len(d1), 2):
	o.append(abs(d1[j - 2][1] - d1[j][1]))
print(sum(o) + sum(e))


ii = lambda : int(input())
mi = lambda : map(int, input().split())
li = lambda : list(mi())
n = ii()
l = li()
d = {}
for i in range(len(l)):
	if l[i] in d:
		d[l[i]].append(i + 1)
	else:
		d[l[i]] = [i + 1]
c = 0
(xi, yi) = [1, 1]
for i in range(1, len(d) + 1):
	(xi1, yi1) = d[i]
	c += min(abs(xi - xi1) + abs(yi - yi1), abs(xi - yi1) + abs(yi - xi1))
	(xi, yi) = (xi1, yi1)
print(c)


class House:
	c = 0

	def __init__(self, val):
		self.id = House.c + 1
		self.val = int(val)
		House.c += 1
n = int(input())
a = list(map(House, input().split()))
a.sort(key=lambda x: x.val)
length = 0
pos1 = pos2 = 1
for i in range(n * 2):
	if i % 2:
		length += abs(pos2 - a[i].id)
		pos2 = a[i].id
	else:
		length += abs(pos1 - a[i].id)
		pos1 = a[i].id
print(length)


class Heap:

	def __init__(self, arr, key=None, heap_type='min'):
		self.arr = arr
		self.key = key
		self.heap_type = heap_type
		if key == None:
			self.key = lambda x: x
		self.heapify()

	def __repr__(self):
		return str(self.arr)

	def __compare(self, index1, index2):
		return self.__compare_keys(self[index1], self[index2])

	def __compare_keys(self, key1, key2):
		ans = 0
		if key1 > key2:
			ans = 1
		elif key1 < key2:
			ans = -1
		else:
			ans = 0
		return ans if self.heap_type == 'min' else -1 * ans

	def heapify(self):
		for i in range(0, len(self)):
			self.__bubble_up(i)

	def insert(self, item):
		self.arr.append(item)
		self.__bubble_up(len(self) - 1)

	def __getitem__(self, index):
		return self.key(self.arr[index])

	def __bubble_up(self, index):
		parent = (index - 1) // 2
		while parent >= 0 and self.__compare(index, parent) == -1:
			(self.arr[parent], self.arr[index]) = (self.arr[index], self.arr[parent])
			(index, parent) = (parent, (parent - 1) // 2)

	def __bubble_down(self, index):
		high = len(self)
		while True:
			(l, r) = (index * 2 + 1, index * 2 + 2)
			if r < high:
				if self.__compare(r, l) == -1:
					if self.__compare(r, index) >= 0:
						break
					(self.arr[r], self.arr[index]) = (self.arr[index], self.arr[r])
					index = r
				else:
					if self.__compare(l, index) >= 0:
						break
					(self.arr[l], self.arr[index]) = (self.arr[index], self.arr[l])
					index = l
			elif l < high:
				if self.__compare(l, index) >= 0:
					break
				(self.arr[l], self.arr[index]) = (self.arr[index], self.arr[l])
				break
			else:
				break

	def __len__(self):
		return len(self.arr)

	def pop(self):
		(self.arr[0], self.arr[-1]) = (self.arr[-1], self.arr[0])
		top = self.arr.pop(-1)
		self.__bubble_down(0)
		return top
n = int(input())
arr = list(map(int, input().split()))
heap = Heap([])
for i in range(2 * n):
	heap.insert((arr[i], i))
(d_a, d_b) = (0, 0)
(l_a, l_b) = (0, 0)
while len(heap) > 0:
	(_, x) = heap.pop()
	d_a += abs(x - l_a)
	l_a = x
	(_, x) = heap.pop()
	d_b += abs(x - l_b)
	l_b = x
print(d_a + d_b)


def res():
	n = int(input())
	x = list(map(int, input().split(' ')))
	dict = {}
	k = 2 * n
	for _ in range(2 * n):
		if dict.get(x[_]):
			dict[x[_]].append(_)
		else:
			dict[x[_]] = []
			dict[x[_]].append(_)
	cost1 = 0
	cur1 = 0
	cur2 = 0
	for i in range(1, n + 1):
		a = dict[i][0]
		b = dict[i][1]
		c = abs(a - cur1) + abs(b - cur2)
		d = abs(a - cur2) + abs(b - cur1)
		if c > d:
			cost1 = cost1 + d
			cur1 = b
			cur2 = a
		else:
			cost1 = cost1 + c
			cur1 = a
			cur2 = b
	print(cost1)
res()


n = int(input())
a = list(map(int, input().split()))
l = [[i + 1, 0, 0] for i in range(n)]
p = q = r = s = 1
for i in range(2 * n):
	if l[a[i] - 1][1] == 0:
		l[a[i] - 1][1] = i + 1
		a[i] = -1
for i in range(2 * n):
	if a[i] != -1:
		if l[a[i] - 1][2] == 0:
			l[a[i] - 1][2] = i + 1
			a[i] = -1
ans = 0
z = 1
for i in range(n):
	ans += abs(l[i][1] - z)
	z = l[i][1]
z = 1
for i in range(n):
	ans += abs(l[i][2] - z)
	z = l[i][2]
print(ans)


from collections import defaultdict
n = int(input())
arr = list(map(int, input().split()))
d = defaultdict(list)
for i in range(2 * n):
	d[arr[i]].append(i)
(ans1, ans2) = (0, 0)
(prev1, prev2) = (0, 0)
for i in range(1, n + 1):
	ans1 += abs(prev1 - d[i][0])
	ans2 += abs(prev2 - d[i][1])
	prev1 = d[i][0]
	prev2 = d[i][1]
print(ans1 + ans2)


a = int(input())
z = list(map(int, input().split()))
v = [[y, x] for (x, y) in enumerate(z)]
v.sort()
z = v[0][1] + v[1][1]
for j in range(0, a * 2 - 2, 2):
	w = abs(v[j + 2][1] - v[j][1]) + abs(v[j + 3][1] - v[j + 1][1])
	e = abs(v[j + 2][1] - v[j + 1][1]) + abs(v[j + 3][1] - v[j][1])
	z += min(w, e)
print(z)


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)


n = int(input())
a = [int(i) for i in input().split()]
b = [0] * n
for i in range(n):
	b[i] = []
for i in range(2 * n):
	b[a[i] - 1] += [i]
c = b[0][0] + b[0][1]
for i in range(1, n):
	c += min(abs(b[i][0] - b[i - 1][0]) + abs(b[i][1] - b[i - 1][1]), abs(b[i][0] - b[i - 1][1]) + abs(b[i][1] - b[i - 1][0]))
print(c)


n = int(input())
A = [int(n) for n in input().split()]
dp = [[0, 1] for _ in range(n + 1)]
to = [j for (j, a) in enumerate(A) if a == 1]
dp[1][0] = to[0] + to[1]
dp[1][1] = to[0] + to[1]
index = [[] for _ in range(n + 1)]
for (i, a) in enumerate(A):
	index[a].append(i)
for i in range(2, n + 1):
	z_z = abs(index[i][0] - index[i - 1][0])
	z_o = abs(index[i][0] - index[i - 1][1])
	o_z = abs(index[i][1] - index[i - 1][0])
	o_o = abs(index[i][1] - index[i - 1][1])
	dp[i][0] = min(dp[i - 1][0] + z_z + o_o, dp[i - 1][1] + z_o + o_z)
	dp[i][1] = min(dp[i - 1][0] + z_o + o_z, dp[i - 1][1] + z_z + o_o)
ans = min(dp[n][0], dp[n][1])
print(ans)


n = int(input())
l = list(map(int, input().split()))
first = [-1] * (n + 1)
second = [-1] * (n + 1)
ans1 = 0
ans2 = 0
for i in range(2 * n):
	if first[l[i]] == -1:
		first[l[i]] = i + 1
	else:
		second[l[i]] = i + 1
cur1 = 1
cur2 = 1
for i in range(1, n + 1):
	ans1 += abs(cur1 - first[i])
	cur1 = first[i]
	ans1 += abs(cur2 - second[i])
	cur2 = second[i]
cur1 = 1
cur2 = 1
for i in range(1, n + 1):
	ans2 += abs(cur2 - first[i])
	cur2 = first[i]
	ans2 += abs(cur1 - second[i])
	cur1 = second[i]
print(min(ans1, ans2))


import sys
from collections import defaultdict as dd
from itertools import permutations as pp
from itertools import combinations as cc
from collections import Counter as ccd
from random import randint as rd
from bisect import bisect_left as bl
import heapq
mod = 10 ** 9 + 7

def ri(flag=0):
	if flag == 0:
		return [int(i) for i in sys.stdin.readline().split()]
	else:
		return int(sys.stdin.readline())
n = ri(1)
a = ri()
k = []
for i in range(2 * n):
	k.append((a[i], i))
k.sort()
sain = 0
diin = 0
ans = 0
f = 0
for i in range(2 * n):
	if f == 0:
		ans += abs(sain - k[i][1])
		f ^= 1
		sain = k[i][1]
	else:
		ans += abs(diin - k[i][1])
		f ^= 1
		diin = k[i][1]
print(ans)


from collections import defaultdict
n = int(input())
a = [int(i) for i in input().split()]
d = defaultdict(list)
for i in range(len(a)):
	d[a[i]].append(i)
i = 1
cur = 0
count = 0
while i <= n:
	count += abs(d[i][0] - cur)
	cur = d[i][0]
	del d[i][0]
	i += 1
i = 1
cur = 0
while i <= n:
	count += abs(d[i][0] - cur)
	cur = d[i][0]
	del d[i][0]
	i += 1
print(count)


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)


import sys
n = int(input())
arr = list(map(int, input().split(' ')))
pos = [[] for i in range(n)]
for i in range(2 * n):
	pos[arr[i] - 1].append(i + 1)
start = 1
res = 0
for i in range(n):
	res += abs(start - pos[i][0])
	start = pos[i][0]
	pos[i][0] = sys.maxsize
start = 1
for i in range(n):
	res += abs(start - pos[i][1])
	start = pos[i][1]
	pos[i][1] = sys.maxsize
print(res)


import math
n = int(input())
arr = list(map(int, input().split()))
d = []
for i in range(2 * n + 1):
	d.append([])
for i in range(len(arr)):
	d[arr[i]].append(i)
for i in range(len(d)):
	d[i].sort()
a = 0
pra = 0
prb = 0
b = 0
for i in range(len(d)):
	if len(d[i]) > 0:
		a += abs(d[i][0] - pra)
		b += abs(d[i][1] - prb)
		pra = d[i][0]
		prb = d[i][1]
print(a + b)


N = int(input())
a = list(map(int, input().split()))
(left, right) = ([0] + [-1] * N, [0] + [-1] * N)
for (i, n) in enumerate(a):
	if left[n] == -1:
		left[n] = i
	else:
		right[n] = i
ans = 0
for (p, c) in zip(left, left[1:]):
	ans += c - p if c > p else p - c
for (p, c) in zip(right, right[1:]):
	ans += c - p if c > p else p - c
print(ans)


n = int(input())
L = list(map(int, input().split()))
I = []
for _ in range(n):
	I.append([])
for i in range(len(L)):
	I[L[i] - 1].append(i + 1)
d = 0
p1 = 1
p2 = 1
for i in range(n):
	d1 = abs(I[i][0] - p1) + abs(I[i][1] - p2)
	d2 = abs(I[i][1] - p1) + abs(I[i][0] - p2)
	if d1 < d2:
		d += d1
		p1 = I[i][0]
		p2 = I[i][1]
	else:
		d += d2
		p1 = I[i][1]
		p2 = I[i][0]
print(d)


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


n = int(input())
a = list(map(int, input().split()))
b = []
for i in range(len(a)):
	b.append([a[i], i])
b.sort()
s = b[0][1]
sdash = b[1][1]
for i in range(2, len(b), 2):
	x = abs(b[i][1] - b[i - 2][1])
	s += x
for i in range(3, len(b), 2):
	x = abs(b[i][1] - b[i - 2][1])
	sdash += x
print(s + sdash)


n = int(input().strip())
cakes = [int(i) for i in input().strip().split()]
num_dict = dict()
for (index, i) in enumerate(cakes, 0):
	if i not in num_dict:
		num_dict[i] = [index]
	else:
		num_dict[i].append(index)
(cake1, cake2) = (0, 0)
(s, d) = (0, 0)
distance = 0
for i in range(1, n + 1):
	if abs(s - num_dict[i][0]) + abs(d - num_dict[i][1]) < abs(s - num_dict[i][1]) + abs(d - num_dict[i][0]):
		distance += abs(s - num_dict[i][0]) + abs(d - num_dict[i][1])
		s = num_dict[i][0]
		d = num_dict[i][1]
	else:
		distance += abs(s - num_dict[i][1]) + abs(d - num_dict[i][0])
		s = num_dict[i][1]
		d = num_dict[i][0]
print(distance)


import math
n = int(input())
a = list(map(int, input().split(' ')))
d = {}
count = 0
for i in range(2 * n):
	if a[i] not in d.keys():
		d[a[i]] = [i]
	else:
		d[a[i]].append(i)
		d[a[i]].sort()
(e, f) = (0, 0)
for i in sorted(d.keys()):
	count += abs(d[i][0] - e) + abs(d[i][1] - f)
	(e, f) = (d[i][0], d[i][1])
print(count)


tiers = int(input())
shops = [int(x) for x in input().split(' ')]
left = [-1] * tiers
right = [0] * tiers
distance = 0
for i in range(2 * tiers):
	a = shops[i] - 1
	if left[a] < 0:
		left[a] = i
	else:
		right[a] = i
left = [0] + left
right = [0] + right
for i in range(tiers):
	l = abs(left[i + 1] - left[i])
	r = abs(right[i + 1] - right[i])
	distance += l + r
print(distance)


b = int(input())
c = list(map(int, input().split()))
d = [i[0] for i in sorted(enumerate(c), key=lambda x: x[1])]
t = d[0]
y = d[1]
for i in range(2, len(d) - 1, 2):
	t = t + abs(d[i - 2] - d[i])
for i in range(3, len(d), 2):
	y = y + abs(d[i - 2] - d[i])
print(t + y)


n = int(input())
a = [int(x) for x in input().split()]
t = []
for i in range(len(a)):
	t.append((a[i], i))
t.sort()
sd = 0
dd = 0
s = 0
d = 0
for i in range(0, 2 * n, 2):
	d1 = abs(t[i][1] - s)
	d2 = abs(t[i + 1][1] - s)
	d3 = abs(t[i][1] - d)
	d4 = abs(t[i + 1][1] - d)
	if d1 + d4 < d2 + d3:
		s = t[i][1]
		sd += d1
		dd += d4
		d = t[i + 1][1]
	else:
		s = t[i + 1][1]
		sd += d2
		dd += d3
		d = t[i][1]
print(sd + dd)


import sys
import math as mt
input = sys.stdin.buffer.readline
t = 1
for ___ in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	d = {}
	for i in range(1, n + 1):
		d[i] = []
	for i in range(2 * n):
		d[l[i]].append(i)
	ans = 0
	s = [0] * (n + 1)
	ng = [0] * (n + 1)
	s[1] = d[1][0]
	ng[1] = d[1][1]
	ans += d[1][0] + d[1][1]
	for i in range(2, n + 1):
		if abs(s[i - 1] - d[i][0]) + abs(ng[i - 1] - d[i][1]) < abs(s[i - 1] - d[i][1]) + abs(ng[i - 1] - d[i][0]):
			s[i] = d[i][0]
			ng[i] = d[i][1]
		else:
			s[i] = d[i][1]
			ng[i] = d[i][0]
		ans += abs(s[i] - s[i - 1]) + abs(ng[i] - ng[i - 1])
	print(ans)


from collections import defaultdict

def main():
	n = int(input())
	a = list(map(int, input().split()))
	size_pos = defaultdict(list)
	for (i, v) in enumerate(a):
		size_pos[v].append(i + 1)
	ret = 0
	for _ in range(2):
		prev = 1
		for i in range(1, n + 1):
			curr = size_pos[i][-1]
			size_pos[i].pop()
			ret += abs(prev - curr)
			prev = curr
	print(ret)
main()


n = int(input())
nums = list(map(int, input().split()))
pos = {}
for i in range(len(nums)):
	if nums[i] in pos.keys():
		pos[nums[i]] += [i]
	else:
		pos[nums[i]] = [i]
result = 0
for i in range(1, n):
	prev_pos = pos[i]
	aft_pos = pos[i + 1]
	result += abs(aft_pos[0] - prev_pos[0]) + abs(aft_pos[1] - prev_pos[1])
result += pos[1][0] + pos[1][1]
print(result)


n = int(input())
arr = list(map(int, input().split(' ')))
mapi = [[] for _ in range(n + 1)]
for (idx, num) in enumerate(arr):
	mapi[num].append(idx)
(start1, start2) = mapi[1]
cost = start1 + start2
for i in range(2, n + 1):
	(c1, c2) = mapi[i]
	val1 = abs(start1 - c1) + abs(start2 - c2)
	val2 = abs(start1 - c2) + abs(start2 - c1)
	cost += min(val1, val2)
	(start1, start2) = (c1, c2)
print(cost)


n = int(input())
a = list(map(int, input().split()))
b = []
for i in range(n + 1):
	b.append([])
for i in range(2 * n):
	b[a[i]].append(i)
total = 0
temp1 = 0
temp2 = 0
for i in range(1, n + 1):
	if abs(b[i][0] - temp1) + abs(b[i][1] - temp2) >= abs(b[i][1] - temp1) + abs(b[i][0] - temp2):
		total += abs(temp1 - b[i][1]) + abs(temp2 - b[i][0])
		temp1 = b[i][1]
		temp2 = b[i][0]
	else:
		total += abs(temp1 - b[i][0]) + abs(tem2 - b[i][1])
		temp1 = b[i][0]
		temp2 = b[i][1]
print(total)


def solve(array, size):
	houses = {}
	for i in range(size):
		tier = array[i]
		houses.setdefault(tier, []).append(i)
	dist = 0
	oldsasha = 0
	olddima = 0
	for key in sorted(houses.keys()):
		(sasha, dima) = houses[key]
		dist += abs(sasha - oldsasha) + abs(dima - olddima)
		oldsasha = sasha
		olddima = dima
	return dist
size = int(input().strip())
array = input().strip().split()
array = [int(array[i]) for i in range(2 * size)]
print(solve(array, 2 * size))


n = int(input())
line = list(map(int, input().split()))
line2 = [[] for s in range(n)]
(S, D, sum) = (0, 0, 0)
for i in range(2 * n):
	line2[line[i] - 1].append(i)
for i in range(n):
	sum += min(abs(S - line2[i][0]) + abs(D - line2[i][1]), abs(S - line2[i][1]) + abs(D - line2[i][0]))
	(S, D) = line2[i]
print(sum)


from collections import defaultdict
n = int(input())
a = [int(i) for i in input().split(' ')]

def helper(a, n):
	lookup = defaultdict(list)
	for (i, num) in enumerate(a):
		lookup[num].append(i)
	lookup[0] = [0, 0]
	res = 0
	for i in range(n):
		(xi, xj, yi, yj) = lookup[i] + lookup[i + 1]
		res += min(abs(xi - yi) + abs(xj - yj), abs(xi - yj) + abs(xj - yi))
	return res
print(helper(a, n))


def main():
	n = int(input())
	tier1 = {}
	tier2 = {}
	for i in range(1, n + 1):
		tier1[i] = -1
		tier2[i] = -1
	arr = list(map(int, input().split()))
	for i in range(2 * n):
		curr = arr[i]
		if tier1[curr] == -1:
			tier1[curr] = i
		else:
			tier2[curr] = i
	a = 0
	b = 0
	distance = 0
	for i in range(n):
		num = i + 1
		x = tier1[num]
		y = tier2[num]
		val1 = abs(x - a) + abs(y - b)
		val2 = abs(x - b) + abs(y - a)
		if val1 <= val2:
			a = x
			b = y
		else:
			a = y
			b = x
		distance += min(val1, val2)
	print(distance)
main()


n = int(input())
d = dict()
l = list(map(int, input().split()))
for (index, i) in enumerate(l):
	if i not in d:
		d[i] = [index]
	else:
		d[i].append(index)
ans = d[1][0] + d[1][1]
for i in range(2, n + 1):
	ans += abs(d[i][0] - d[i - 1][0]) + abs(d[i][1] - d[i - 1][1])
print(ans)


from heapq import heappush, heappop
n = int(input())
arr = list(map(int, input().split()))
heap = []
for i in range(2 * n):
	heappush(heap, (arr[i], i))
(d_a, d_b) = (0, 0)
(l_a, l_b) = (0, 0)
while len(heap) > 0:
	(_, x) = heappop(heap)
	d_a += abs(x - l_a)
	l_a = x
	(_, x) = heappop(heap)
	d_b += abs(x - l_b)
	l_b = x
print(d_a + d_b)


n = int(input()) + 1
s = [0] * n
d = [0] * n
a = [int(i) for i in input().split()]
k = 1
for i in a:
	if not s[i]:
		s[i] = k
	else:
		d[i] = k
	k += 1
p = -2
for i in range(1, n):
	p += abs(s[i] - s[i - 1]) + abs(d[i] - d[i - 1])
print(p)


def main():
	n = int(input())
	a = list(map(int, input().split()))
	new = []
	ind = 0
	for num in a:
		new.append((num, ind))
		ind += 1
	new.sort()
	ind_list = []
	for (x, y) in new:
		ind_list.append(y)
	i = start1 = start2 = ans1 = ans2 = 0
	while i < n * 2:
		if i % 2 != 0:
			distance1 = ind_list[i] - start1
			start1 = ind_list[i]
			if distance1 < 0:
				distance1 = distance1 * -1
			ans1 = ans1 + distance1
			i += 1
		else:
			distance2 = ind_list[i] - start2
			start2 = ind_list[i]
			if distance2 < 0:
				distance2 = distance2 * -1
			ans2 = ans2 + distance2
			i += 1
	print(ans1 + ans2)
main()


from math import ceil
n = int(input())
a = list(map(int, input().split()))
(x, y) = ([0] * n, [0] * n)
for i in range(2 * n):
	if x[a[i] - 1] != 0:
		y[a[i] - 1] = i + 1
	else:
		x[a[i] - 1] = i + 1
count = 0
pos1 = 0
pos2 = 0
for i in range(n):
	count += abs(x[i] - 1 - pos1)
	pos1 = x[i] - 1
	count += abs(y[i] - 1 - pos2)
	pos2 = y[i] - 1
print(count)


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)
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())
bakeries_iter = (int(i) for i in input().split())
sasha = 0
dima = 0
steps = 0
bakeries = {}
for (i, v) in enumerate(bakeries_iter):
	if v in bakeries:
		bakeries[v].append(i)
	else:
		bakeries[v] = [i]
for tier in range(1, n + 1):
	arrangement1 = abs(sasha - bakeries[tier][0]) + abs(dima - bakeries[tier][1])
	arrangement2 = abs(sasha - bakeries[tier][1]) + abs(dima - bakeries[tier][0])
	if arrangement1 < arrangement2:
		steps += arrangement1
		sasha = bakeries[tier][0]
		dima = bakeries[tier][1]
	else:
		steps += arrangement2
		sasha = bakeries[tier][1]
		dima = bakeries[tier][0]
print(steps)


n = int(input())
arr = list(map(int, input().split()))
pos = [[0, 0] for _ in range(n + 1)]
for i in range(2 * n):
	x = arr[i]
	if pos[x][0] == 0:
		pos[x][0] = i
	else:
		pos[x][1] = i
dp = [[0 for _ in range(2)] for _ in range(n + 1)]
dp[n][0] = 0
dp[n][1] = 0
for i in range(n - 1, -1, -1):
	for j in range(2):
		v1 = dp[i + 1][j] + abs(pos[i][j] - pos[i + 1][j]) + abs(pos[i][1 - j] - pos[i + 1][1 - j])
		v2 = dp[i + 1][1 - j] + abs(pos[i][j] - pos[i + 1][1 - j]) + abs(pos[i][1 - j] + pos[i + 1][j])
		dp[i][j] = min(v1, v2)
print(min(dp[0][0], dp[0][1]))


n = int(input())
a = [int(j) for j in input().split()]
fre = [[] for j in range(n)]
for x in range(2 * n):
	fre[a[x] - 1] += [x]
su1 = fre[0][0]
su2 = fre[0][1]
for i in range(1, n):
	su1 += abs(fre[i - 1][0] - fre[i][0])
	su2 += abs(fre[i - 1][1] - fre[i][1])
print(su1 + su2)


n = int(input())
an = list(map(int, input().split()))
dis = [[0, 0] for i in range(n)]
for i in range(n * 2):
	now = an[i] - 1
	if dis[now][0] != 0:
		dis[now][1] = i + 1
	else:
		dis[now][0] = i + 1
last = [1, 1]
res = 0
for (a, b) in dis:
	res += min(abs(a - last[0]) + abs(b - last[1]), abs(b - last[0]) + abs(a - last[1]))
	last = [a, b]
print(res)


__author__ = 'NIORLYS'
n = int(input())
a = list(map(int, input().split()))
d = {}
for i in range(2 * n):
	if not a[i] in d:
		d[a[i]] = i
		if len(d) == n:
			break
sasha = d[1]
for i in range(2, n + 1):
	sasha += abs(d[i] - d[i - 1])
for i in range(2 * n):
	if d[a[i]] != i:
		d[a[i]] = i
dima = d[1]
for i in range(2, n + 1):
	dima += abs(d[i] - d[i - 1])
print(sasha + dima)


n = int(input())
houses = [int(i) for i in input().split()]
layers = {k: [] for k in range(0, n + 1)}
distance = 0
layers[0] = [0, 0]
for i in range(2 * n):
	layers[houses[i]].append(i)
for i in range(0, n):
	for j in range(2):
		distance += abs(layers[i][j] - layers[i + 1][j])
print(distance)


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)


from bisect import bisect_right as br
from bisect import bisect_left as bl
from collections import defaultdict
from itertools import *
import functools
import sys
import math
MAX = sys.maxsize
MAXN = 10 ** 6 + 10
MOD = 10 ** 9 + 7

def isprime(n):
	n = abs(int(n))
	if n < 2:
		return False
	if n == 2:
		return True
	if not n & 1:
		return False
	for x in range(3, int(n ** 0.5) + 1, 2):
		if n % x == 0:
			return False
	return True

def mhd(a, b, x, y):
	return abs(a - x) + abs(b - y)

def numIN():
	return map(int, sys.stdin.readline().strip().split())

def charIN():
	return sys.stdin.readline().strip().split()

def chk(x, y):
	print(x, '=', y)

def ncr(n, k):
	res = 1
	c = [0] * (k + 1)
	c[0] = 1
	for i in range(1, n + 1):
		for j in range(min(i, k), 0, -1):
			c[j] = (c[j] + c[j - 1]) % MOD
	return c[k]

def diff(a, b):
	return (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2
n = int(input())
l = list(numIN())
d = defaultdict(list)
for i in range(2 * n):
	d[l[i]].append(i + 1)
ans = sum(d[1]) - 2
i = 2
while i <= n:
	ans += min(abs(d[i][0] - d[i - 1][0]) + abs(d[i][1] - d[i - 1][1]), abs(d[i][0] - d[i - 1][1]) + abs(d[i][1] - d[i - 1][0]))
	i += 1
print(ans)


n = int(input())
tmp = map(int, input().split())
arr = [[] for i in range(n + 1)]
arr[0].append(1)
arr[0].append(1)
idx = 1
for i in tmp:
	arr[i].append(idx)
	idx += 1
sum1 = 0
sum2 = 0
for i in range(1, n + 1):
	sum1 += abs(arr[i][0] - arr[i - 1][0])
	sum2 += abs(arr[i][1] - arr[i - 1][1])
print(sum1 + sum2)


n = int(input())
numbers = list(map(int, input().split()))
y = 0
wynik = 0
bliz = [0] * (n + 1)
dal = [0] * (n + 1)
odw = [0] * (n + 1)
for i in range(0, 2 * n):
	y = numbers[i]
	if odw[y] == 0:
		bliz[y] = i
		odw[y] = 1
	else:
		dal[y] = i
b0 = bliz[1]
d0 = dal[1]
wynik = bliz[1] + dal[1]
for i in range(2, n + 1):
	b1 = bliz[i]
	d1 = dal[i]
	wynik = wynik + min(abs(b1 - b0) + abs(d1 - d0), abs(b1 - d0) + abs(d1 - b0))
	d0 = d1
	b0 = b1
print(wynik)


n = int(input())
seq = list(map(int, input().split()))
dseq = {}
for i in range(len(seq)):
	s = seq[i]
	try:
		dseq[s].append(i)
	except KeyError:
		dseq[s] = [i]
ans = 0
cura = 0
curb = 0
for i in range(1, n + 1):
	if abs(cura - dseq[i][0]) + abs(curb - dseq[i][1]) < abs(cura - dseq[i][1]) + abs(curb - dseq[i][0]):
		ans += abs(cura - dseq[i][0])
		ans += abs(curb - dseq[i][1])
		cura = dseq[i][0]
		curb = dseq[i][1]
	else:
		ans += abs(cura - dseq[i][1])
		ans += abs(curb - dseq[i][0])
		cura = dseq[i][1]
		curb = dseq[i][0]
print(ans)


import sys

class Main:

	def __init__(self):
		self.buff = None
		self.index = 0

	def next(self):
		if self.buff is None or self.index == len(self.buff):
			self.buff = sys.stdin.readline().split()
			self.index = 0
		val = self.buff[self.index]
		self.index += 1
		return val

	def next_int(self):
		return int(self.next())

	def cal(self, s):
		if len(s) == 1:
			return s[0]
		if s[0] == 0:
			return self.cal(s[1:])
		v = 1
		for c in s:
			v *= c
		return v

	def solve(self):
		n = self.next_int()
		x = [self.next_int() for _ in range(0, 2 * n)]
		id = sorted([i for i in range(0, 2 * n)], key=lambda i: x[i])
		sum = 0
		x = 0
		y = 0
		for i in range(0, 2 * n, 2):
			sum += min(abs(x - id[i]) + abs(y - id[i + 1]), abs(x - id[i + 1]) + abs(y - id[i]))
			x = id[i]
			y = id[i + 1]
		print(sum)
Main().solve()


from collections import defaultdict
n = int(input())
l = list(map(int, input().split()))
di = defaultdict(list)
for j in range(2 * n):
	di[l[j]].append(j)
start = 0
tot = 0
for j in range(1, n + 1):
	tot += abs(min(di[j]) - start)
	start = min(di[j])
start = 0
for j in range(1, n + 1):
	tot += abs(max(di[j]) - start)
	start = max(di[j])
print(tot)


import sys, itertools, math, collections

def ia():
	return [int(i) for i in sys.stdin.readline().strip().split(' ')]

def ii():
	return int(sys.stdin.readline().strip())

def istr():
	return sys.stdin.readline().strip()
n = ii()
A = ia()
P = collections.defaultdict(list)
for (i, a) in enumerate(A):
	P[a].append(i)
ans = 0
(p1, p2) = (0, 0)
for i in range(1, n + 1):
	h = P[i]
	d1 = abs(p1 - h[0])
	d2 = abs(p2 - h[0])
	d3 = abs(p1 - h[1])
	d4 = abs(p2 - h[1])
	if d1 + d4 < d2 + d3:
		p1 = h[0]
		p2 = h[1]
		ans += d1 + d4
	else:
		p1 = h[1]
		p2 = h[0]
		ans += d2 + d3
print(ans)


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


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


from collections import defaultdict
n = int(input())
a = defaultdict(list)
k = -1
for i in input().split():
	k += 1
	i = int(i)
	a[i - 1].append(k)
s1 = 0
s2 = 0
k1 = 0
k2 = 0
for i in range(n):
	s1 += abs(a[i][0] - k1)
	k1 = a[i][0]
	s2 += abs(a[i][1] - k2)
	k2 = a[i][1]
print(s1 + s2)


n = int(input())
x = list(map(int, input().split()))
a = []
for i in range(2 * n):
	a.append([0, 0])
for j in range(2 * n):
	if a[x[j]][0] == 0:
		a[x[j]][0] = j + 1
	else:
		if a[x[j]][0] > j + 1:
			a[x[j]][1] = a[x[j]][0]
			a[x[j]][0] = j + 1
		a[x[j]][1] = j + 1
ans1 = ans2 = -1
for k in range(1, n + 1):
	ans1 += abs(a[k][0] - a[k - 1][0])
	ans2 += abs(a[k][1] - a[k - 1][1])
print(ans1 + ans2)


import math
from collections import defaultdict as df
from sys import stdin
n = int(stdin.readline())
a = list(map(int, input().rstrip().split()))
d = df(list)
for i in range(len(a)):
	d[a[i]].append(i)
dima = [0] * (n + 1)
sasha = [0] * (n + 1)
prev1 = 0
prev2 = 0
dis = 0
for i in range(1, n + 1):
	if sasha[i] == 0 and dima[i] == 0:
		sasha[i] = 1
		dis += abs(prev1 - d[i][0])
		prev1 = d[i][0]
	if sasha[i] == 1 and dima[i] == 0:
		dima[i] = 1
		dis += abs(prev2 - d[i][1])
		prev2 = d[i][1]
print(dis)


from collections import defaultdict
N = int(input())
a = [int(x) for x in input().split()]
table = defaultdict(list)
for (i, ai) in enumerate(a):
	table[ai].append(i)
total = 0
old = (0, 0)
for i in range(1, N + 1):
	new = tuple(table[i])
	arr = [(old[0], 'o'), (old[1], 'o'), (new[0], 'n'), (new[1], 'n')]
	arr.sort()
	s = ''.join([pair[1] for pair in arr])
	if s == 'oonn' or s == 'nnoo':
		total += arr[2][0] - arr[0][0]
		total += arr[3][0] - arr[1][0]
	if s == 'onon' or s == 'nono' or s == 'onno' or (s == 'noon'):
		total += arr[1][0] - arr[0][0]
		total += arr[3][0] - arr[2][0]
	old = new
print(total)


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 = [*map(int, input().split())]
x = []
for i in range(2 * n):
	x.append([a[i], i])
x.sort()
b = x[0][1] + x[1][1]
for i in range(len(x) - 2):
	b += abs(x[i + 2][1] - x[i][1])
print(b)


n = int(input())
a = list(map(int, input().split()))
b = list(enumerate(a))
b.sort(key=lambda x: x[1])
i = 0
ans = b[0][0] + b[1][0]
while i < 2 * n - 3:
	x = min(abs(b[i][0] - b[i + 2][0]) + abs(b[i + 1][0] - b[i + 3][0]), abs(b[i][0] - b[i + 3][0]) + abs(b[i + 1][0] - b[i + 2][0]))
	ans += x
	i += 2
print(ans)


n = int(input())
a = list(map(int, input().split()))
g1 = [[0, 0]]
g2 = [[0, 0]]
used = set()
for i in range(len(a)):
	if a[i] not in used:
		g1.append([a[i], i])
		used.add(a[i])
	else:
		g2.append([a[i], i])
g1.sort()
g2.sort()
ans = 0
for i in range(0, n):
	ans += abs(g1[i][1] - g1[i + 1][1])
	ans += abs(g2[i][1] - g2[i + 1][1])
print(ans)


n = int(input())
a = list(map(int, input().split()))
b = [0] * (n + 1)
c = [0] * (n + 1)
d = [False] * (n + 1)
for i in range(2 * n):
	if not d[a[i]]:
		b[a[i]] = i
		d[a[i]] = True
	else:
		c[a[i]] = i
ans = 0
for i in range(n):
	ans += abs(b[i] - b[i + 1])
	ans += abs(c[i] - c[i + 1])
print(ans)


n = int(input())
l = map(int, input().split())
d = {}
d.update({0: [1, 1]})
for (i, j) in enumerate(l, 1):
	try:
		d[j][1] = i
	except KeyError:
		d[j] = [i, -1]
c = 0
(xi, yi) = d[0]
for i in range(1, len(d)):
	(xi1, yi1) = d[i]
	c += min(abs(xi - xi1) + abs(yi - yi1), abs(xi - yi1) + abs(yi - xi1))
	(xi, yi) = (xi1, yi1)
print(c)


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


(n, ls) = (int(input()), list(map(int, input().split())))
d = {i: [] for i in range(n)}
for i in range(2 * n):
	d[ls[i] - 1].append(i)
l1 = l2 = td = 0
for i in range(n):
	nl = d[i]
	td += min(abs(nl[0] - l1) + abs(nl[1] - l2), abs(nl[0] - l2) + abs(nl[1] - l1))
	(l1, l2) = nl
print(td)


import sys
n = int(sys.stdin.readline())
a = [int(tmp) for tmp in sys.stdin.readline().split()]
o = [-1] * (2 * n + 2)
for i in range(2 * n):
	if o[a[i] * 2] == -1:
		o[a[i] * 2] = i
	elif o[a[i] * 2] < i:
		o[a[i] * 2 + 1] = i
	else:
		(o[a[i] * 2], o[a[i] * 2 + 1]) = (i, o[a[i] * 2])
p1 = 0
p2 = 0
s1 = 0
s2 = 0
for i in range(2, 2 * n + 2, 2):
	s1 += abs(o[i] - p1)
	s2 += abs(o[i + 1] - p2)
	p1 = o[i]
	p2 = o[i + 1]
print(s1 + s2)


n = int(input())
a = list(map(int, input().split()))
(i, j) = (0, 0)
dist = 0
pos = [0] * (n * 2)
for ii in range(len(a)):
	k = pos[a[ii]]
	if k == 0:
		pos[a[ii]] = [ii, 0]
	else:
		pos[a[ii]][1] = ii
for t in range(1, n + 1):
	t1 = pos[t][0]
	t2 = pos[t][1]
	i1 = abs(i - t1) + abs(j - t2)
	i2 = abs(i - t2) + abs(j - t1)
	if i1 < i2:
		dist += i1
		i = t1
		j = t2
	else:
		dist += i2
		i = t2
		j = t1
print(dist)


def go():
	n = int(input())
	a = [int(i) for i in input().split(' ')]
	b = [[] for _ in range(n)]
	for i in range(2 * n):
		b[a[i] - 1].append(i)
	s = 0
	d = 0
	total = 0
	for i in range(n):
		total += abs(b[i][0] - s)
		s = b[i][0]
		total += abs(b[i][1] - d)
		d = b[i][1]
	return total
print(go())


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


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)
x = [j for (i, j) in d.items()]
sasha = x[0][0]
dima = x[0][1]
total = sasha + dima
for i in range(1, n):
	b1 = abs(sasha - x[i][0]) + abs(dima - x[i][1])
	b2 = abs(sasha - x[i][1]) + abs(dima - x[i][0])
	if b1 < b2:
		sasha = x[i][0]
		dima = x[i][1]
		total += b1
	else:
		sasha = x[i][1]
		dima = x[i][0]
		total += b2
print(total)


import math
n = int(input())
a = list(map(int, input().split()))
d = dict()
for i in range(2 * n):
	if a[i] - 1 not in d:
		d[a[i] - 1] = []
	d[a[i] - 1].append(i)
ans = 0
(f, s) = (0, 0)
for i in range(n):
	(x, y) = d[i]
	ans += abs(f - min(x, y)) + abs(s - max(x, y))
	f = min(x, y)
	s = max(x, y)
print(ans)


import sys
lines = sys.stdin.read().splitlines()
n = int(lines[0])
arr = lines[1].split(' ')
torts = {}
for i in range(0, len(arr)):
	l = int(arr[i])
	if l in torts:
		torts[l].append(i)
	else:
		torts[l] = [i]
pos1 = 0
pos2 = 0
dist = 0
for j in range(1, n + 1):
	lpos = min(torts[j])
	rpos = max(torts[j])
	dist += abs(lpos - pos1) + abs(rpos - pos2)
	pos1 = lpos
	pos2 = rpos
print(dist)


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())
a = list(map(int, input().split()))
dic = [[] for i in range(N + 1)]
for i in range(2 * N):
	dic[a[i] - 1].append(i)
(pre1, pre2) = (0, 0)
num = 0
for i in range(N):
	if pre1 == pre2:
		num += abs(dic[i][0] - pre2) + abs(dic[i][1] - pre2)
		pre1 = dic[i][0]
		pre2 = dic[i][1]
	else:
		if pre1 > pre2:
			(pre1, pre2) = (pre2, pre1)
		num += abs(min(dic[i]) - pre1) + abs(max(dic[i]) - pre2)
		(pre1, pre2) = (min(dic[i]), max(dic[i]))
print(num)


n = int(input())
a = list(map(int, input().split()))
hashArr1 = [0] * 100001
hashArr2 = [0] * 100001
for i in range(2 * n):
	if hashArr1[a[i]] == 0:
		hashArr1[a[i]] = i + 1
	else:
		hashArr2[a[i]] = i + 1
prev1 = 1
prev2 = 1
ans = 0
for i in range(n):
	if abs(hashArr1[i + 1] - prev1) + abs(hashArr2[i + 1] - prev2) > abs(hashArr1[i + 1] - prev2) + abs(hashArr2[i + 1] - prev1):
		ans += abs(hashArr1[i + 1] - prev2) + abs(hashArr2[i + 1] - prev1)
		prev1 = hashArr1[i + 1]
		prev2 = hashArr2[i + 1]
	else:
		ans += abs(hashArr1[i + 1] - prev1) + abs(hashArr2[i + 1] - prev2)
		prev2 = hashArr1[i + 1]
		prev1 = hashArr2[i + 1]
print(ans)


n = int(input())
a = list(map(int, input().split()))
D = {}
for i in range(len(a)):
	try:
		D[a[i]] += [i]
	except:
		D[a[i]] = [i]
steps = 0
for i in D.keys():
	try:
		steps += abs(D[i][0] - D[i + 1][0]) + abs(D[i][1] - D[i + 1][1])
	except:
		pass
steps += D[1][0] + D[1][1]
print(steps)


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)


import collections
n = int(input())
a = list(map(int, input().split()))
dic = {}
for i in range(2 * n):
	dic.setdefault(a[i], []).append(i)
(ans, prev1, prev2) = (0, 0, 0)
for i in range(n):
	ans += abs(prev1 - min(dic[i + 1])) + abs(prev2 - max(dic[i + 1]))
	(prev1, prev2) = (min(dic[i + 1]), max(dic[i + 1]))
print(ans)


n = int(input())
a = list(map(int, input().split()))
d = {}
for i in range(len(a)):
	if a[i] in d:
		d[a[i]].append(i + 1)
	else:
		d[a[i]] = [i + 1]
f = 1
s = 1
res = 0
for i in range(1, n + 1):
	(a, b) = d[i]
	if abs(f - a) + abs(s - b) > abs(f - b) + abs(s - a):
		res += abs(f - b) + abs(s - a)
		f = b
		s = a
	else:
		res += abs(f - a) + abs(s - b)
		f = a
		s = 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
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)


n = int(input())
num = input().split(' ')
x1 = 0
x2 = 0
s = 0
places = {}
for j in range(1, n + 1):
	places[j] = []
for i in range(2 * n):
	places[int(num[i])] += [i]
for i in range(n):
	(y1, y2) = (places[i + 1][0], places[i + 1][1])
	(k, h, p, g) = (abs(y1 - x1), abs(y1 - x2), abs(y2 - x1), abs(y2 - x2))
	c = min(k + g, h + p)
	if c == k + g:
		(x1, x2) = (y1, y2)
	else:
		(x1, x2) = (y2, y1)
	s += c
print(s)


n = int(input())
l1 = [0] * n
l2 = [0] * n
a = list(map(int, input().split()))
for i in range(2 * n):
	if l1[a[i] - 1]:
		l2[a[i] - 1] = i
	else:
		l1[a[i] - 1] = i
s = l1[0]
d = l2[0]
for i in range(1, n):
	s1 = abs(l1[i] - l1[i - 1])
	s2 = abs(l2[i] - l1[i - 1])
	d1 = abs(l2[i] - l2[i - 1])
	d2 = abs(l1[i] - l2[i - 1])
	mn1 = s1 + d1
	mn2 = s2 + d2
	if mn1 <= mn2:
		s += s1
		d += d1
	else:
		s += s2
		d += d2
		(l1[i], l2[i]) = (l2[i], l1[i])
print(s + d)


def solve(a, n):
	idx = [[] for i in range(n + 1)]
	idx[0].append(0)
	idx[0].append(0)
	for i in range(2 * n):
		idx[a[i]].append(i)
	res = 0
	(b, c) = (0, 0)
	for (d, e) in idx:
		res += min(abs(b - d) + abs(c - e), abs(b - e) + abs(c - d))
		(b, c) = (d, e)
	return res
n = int(input())
a = list(map(int, input().split()))
print(solve(a, n))


import sys
import math

def solve(a, n):
	prev_pos = [0, 0]
	s = [0, 0]
	for r in range(2):
		for i in range(r, 2 * n, 2):
			s[r] += abs(prev_pos[r] - a[i][1])
			prev_pos[r] = a[i][1]
	return sum(s)
n = int(input())
a = list(map(int, input().split()))
a = sorted(((y, x) for (x, y) in enumerate(a)))
print(solve(a, n))


d = dict()
a = int(input())
for (i, j) in zip(range(1, 2 * a + 1), map(int, input().split())):
	d[j] = d.get(j, ())
	d[j] += (i,)
(s, s1) = d[1]
(x, y) = (s, s1)
s -= 1
s1 -= 1
for j in range(1, a + 1):
	(t, t1) = d[j]
	if abs(x - t) + abs(y - t1) <= abs(y - t) + abs(x - t1):
		s += abs(x - t)
		s1 += abs(y - t1)
		x = t
		y = t1
	else:
		s += abs(x - t1)
		s1 += abs(y - t)
		x = t1
		y = t
print(s + s1)


n = int(input())
a = list(map(int, input().split()))
sasha = [0] * (n + 1)
dima = [0] * (n + 1)
for i in range(2 * n):
	temp = a[i]
	if sasha[temp] == 0:
		sasha[temp] = i + 1
	else:
		dima[temp] = i + 1
sa_in = 1
di_in = 1
total = 0
for i in range(1, n + 1):
	total += abs(sasha[i] - sa_in)
	total += abs(dima[i] - di_in)
	sa_in = sasha[i]
	di_in = dima[i]
print(total)


n = int(input())
A = [[] for i in range(n)]
P = str(input()).split(' ')
for i in range(2 * n):
	A[int(P[i]) - 1].append(i)
x = 0
y = 0
minimal = 0
for i in range(n):
	minimal += min(abs(A[i][0] - x) + abs(A[i][1] - y), abs(A[i][0] - y) + abs(A[i][1] - x))
	(x, y) = (A[i][0], A[i][1])
print(minimal)


from sys import stdin, stdout
import math
N = int(input())
arr = [int(x) for x in stdin.readline().split()]
order = sorted(range(len(arr)), key=lambda k: arr[k])
locate = [order[0], order[1]]
res = order[0] + order[1]
for i in range(1, N):
	A = order[2 * i]
	B = order[2 * i + 1]
	L1 = locate[0]
	L2 = locate[1]
	dist1 = abs(A - L1) + abs(B - L2)
	dist2 = abs(B - L1) + abs(A - L2)
	if dist1 > dist2:
		res += dist2
		locate = [B, A]
	else:
		res += dist1
		locate = [A, B]
print(res)


n = int(input())
l = list(map(int, input().split()))
l1 = []
N = 10000000000000000
for i in range(n * 2):
	l1.append([[l[i] + (i + 1) / N], i])
l1 = sorted(l1, key=lambda x: x[0])
ans = 0
k = 0
for i in range(0, n * 2, 2):
	ans += abs(k - l1[i][1])
	k = l1[i][1]
k = 0
for i in range(1, n * 2, 2):
	ans += abs(k - l1[i][1])
	k = l1[i][1]
print(ans)


n = int(input())
a = list(map(int, input().split()))
cs = [-1] * (n + 1)
cd = [-1] * (n + 1)
for i in range(0, n * 2):
	if cs[a[i]] == -1:
		cs[a[i]] = i
	else:
		cd[a[i]] = i
currS = currD = t = 0
for i in range(1, n + 1):
	t += abs(currS - cs[i])
	currS = cs[i]
	t += abs(currD - cd[i])
	currD = cd[i]
print(t)