Santa has to send presents to the kids. He has a large stack of $n$ presents, numbered from $1$ to $n$; the topmost present has number $a_1$, the next present is $a_2$, and so on; the bottom present has number $a_n$. All numbers are distinct.

Santa has a list of $m$ distinct presents he has to send: $b_1$, $b_2$, ..., $b_m$. He will send them in the order they appear in the list.

To send a present, Santa has to find it in the stack by removing all presents above it, taking this present and returning all removed presents on top of the stack. So, if there are $k$ presents above the present Santa wants to send, it takes him $2k + 1$ seconds to do it. Fortunately, Santa can speed the whole process up — when he returns the presents to the stack, he may reorder them as he wishes (only those which were above the present he wanted to take; the presents below cannot be affected in any way).

What is the minimum time required to send all of the presents, provided that Santa knows the whole list of presents he has to send and reorders the presents optimally? Santa cannot change the order of presents or interact with the stack of presents in any other way.

Your program has to answer $t$ different test cases.


-----Input-----

The first line contains one integer $t$ ($1 \le t \le 100$) — the number of test cases.

Then the test cases follow, each represented by three lines.

The first line contains two integers $n$ and $m$ ($1 \le m \le n \le 10^5$) — the number of presents in the stack and the number of presents Santa wants to send, respectively.

The second line contains $n$ integers $a_1$, $a_2$, ..., $a_n$ ($1 \le a_i \le n$, all $a_i$ are unique) — the order of presents in the stack.

The third line contains $m$ integers $b_1$, $b_2$, ..., $b_m$ ($1 \le b_i \le n$, all $b_i$ are unique) — the ordered list of presents Santa has to send.

The sum of $n$ over all test cases does not exceed $10^5$.


-----Output-----

For each test case print one integer — the minimum number of seconds which Santa has to spend sending presents, if he reorders the presents optimally each time he returns them into the stack.


-----Example-----
Input
2
3 3
3 1 2
3 2 1
7 2
2 1 7 3 4 5 6
3 1

Output
5
8

Difficulty: MEDIUM
Tags: Data structures

Implementation
Skill types: Data structures

Starter code:

Solutions:
q = int(input())
for _ in range(q):
	(n, m) = [int(t) for t in input().split(' ')]
	a = [int(t) for t in input().split(' ')]
	b = [int(t) for t in input().split(' ')]
	level = 0
	plevel = {}
	for (i, ai) in enumerate(a):
		plevel[ai] = i
	summy = 0
	for (step, bi) in enumerate(b):
		if plevel[bi] > level:
			summy += (plevel[bi] - step) * 2 + 1
			level = plevel[bi]
		else:
			summy += 1
	print(summy)


for nt in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	d = {}
	time = 0
	for i in range(n):
		if a[i] != b[0]:
			d[str(a[i])] = 1
		else:
			time += 2 * i + 1
			loc = i
			break
	for i in range(1, m):
		if str(b[i]) in d:
			time += 1
		else:
			for j in range(loc + 1, n):
				if a[j] == b[i]:
					time += 2 * (j - i) + 1
					loc = j
					break
				else:
					d[str(a[j])] = 1
	print(time)


import sys
from math import gcd, sqrt
from typing import DefaultDict
sys.setrecursionlimit(10 ** 5)
inf = float('inf')
en = lambda x: list(enumerate(x))
ii = lambda : int(input())
r = lambda : map(int, input().split())
rr = lambda : list(r())

def solve():
	(n, m) = r()
	arr = rr()
	brr = rr()
	pos = {j: i for (i, j) in enumerate(arr)}
	x = 0
	ans = 0
	for (j, i) in enumerate(brr, 1):
		z = pos[i]
		if z < x:
			ans += 1
		elif z > x:
			ans += (z - j + 1) * 2 + 1
			x = z
		else:
			ans += 1
			x += 1
	print(ans)
for _ in range(ii()):
	solve()


import sys
import collections
t = int(input())
for _ in range(t):
	_ = input()
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	f = collections.defaultdict(bool)
	presents_before = 0
	r = 0
	i = 0
	j = 0
	while j < len(b):
		if b[j] in f:
			presents_before -= 1
			r += 1
		else:
			while a[i] != b[j]:
				f[a[i]] = True
				presents_before += 1
				i += 1
			i += 1
			r += presents_before * 2 + 1
		j += 1
	print(r)


t = int(input())
ans = []
for i in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	c = [0] * n
	for i in range(n):
		c[a[i] - 1] = i
	time = c[b[0] - 1] * 2 + 1
	s = c[b[0] - 1]
	for i in range(1, m):
		if s > c[b[i] - 1]:
			time += 1
		else:
			s = c[b[i] - 1]
			time = time + (c[b[i] - 1] - i) * 2 + 1
	ans.append(time)
for i in range(t):
	print(ans[i])


from collections import deque
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	arr = deque([int(x) for x in input().split()])
	cache = set()
	query = [int(x) for x in input().split()]
	moves = 0
	for x in query:
		if x in cache:
			moves += 1
			cache.remove(x)
		else:
			while arr[0] != x:
				cache.add(arr[0])
				arr.popleft()
			arr.popleft()
			moves += 2 * len(cache) + 1
	print(moves)


for t in range(int(input())):
	(n, m) = map(int, input().split())
	a = [x - 1 for x in list(map(int, input().split()))]
	b = [x - 1 for x in list(map(int, input().split()))]
	pos = a[:]
	for i in range(n):
		pos[a[i]] = i
	lst = -1
	res = m
	for i in range(m):
		if pos[b[i]] > lst:
			res += 2 * (pos[b[i]] - i)
			lst = pos[b[i]]
	print(res)


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = list((x - 1 for x in map(int, input().split())))
	b = list((x - 1 for x in map(int, input().split())))
	d = dict()
	for i in a:
		d[a[i]] = i
	ans = 0
	amin = -1
	ref = 0
	for i in b:
		if d[i] > amin:
			amin = d[i]
			ans += 2 * (amin - ref) + 1
		else:
			ans += 1
		ref += 1
	print(ans)


def process(ref, arr):
	d = {}
	for (i, reff) in enumerate(ref):
		d[reff] = i
	brr = [d[ar] for ar in arr]
	res = 0
	rem = 0
	top = 0
	for br in brr:
		if br < rem:
			res += 1
		else:
			res += 2 * (br - top) + 1
		top += 1
		rem = max(rem, br)
	return res
s = input()
cases = int(s)
for case in range(cases):
	_ = input()
	s = input()
	ref = [int(s) for s in s.split()]
	s = input()
	arr = [int(s) for s in s.split()]
	print(process(ref, arr))


for _ in range(int(input())):
	(k, m) = map(int, input().split())
	s = list(map(int, input().split()))
	ss = list(map(int, input().split()))
	maxx = 0
	ans = 0
	help = 0
	d = [0 for i in range(k + 1)]
	for i in range(k):
		d[s[i]] = i
	for i in range(m):
		ch = d[ss[i]]
		if ch > maxx:
			maxx = ch
			ans += (maxx - help) * 2 + 1
			help += 1
		else:
			ans += 1
			help += 1
	print(ans)


import sys
input = sys.stdin.readline
T = int(input())
for _ in range(T):
	(N, M) = map(int, input().split())
	A = list(map(int, input().split()))
	d = {}
	for (i, a) in enumerate(A):
		d[a] = i
	B = list(map(int, input().split()))
	m_i = 0
	t = 0
	for (j, b) in enumerate(B):
		i = d[b]
		if m_i > i:
			t += 1
		else:
			m_i = i
			t += 2 * (i - j) + 1
	print(t)


from sys import stdin, stdout
from math import floor, gcd, fabs, factorial, fmod, sqrt, inf, log
from collections import defaultdict as dd, deque
from heapq import merge, heapify, heappop, heappush, nsmallest
from bisect import bisect_left as bl, bisect_right as br, bisect
mod = pow(10, 9) + 7
mod2 = 998244353

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

def iinp():
	return int(inp())

def out(var, end='\n'):
	stdout.write(str(var) + '\n')

def outa(*var, end='\n'):
	stdout.write(' '.join(map(str, var)) + end)

def lmp():
	return list(mp())

def mp():
	return map(int, inp().split())

def smp():
	return map(str, inp().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(m, val) for j in range(n)]

def remadd(x, y):
	return 1 if x % y else 0

def ceil(a, b):
	return (a + b - 1) // b
S1 = 'abcdefghijklmnopqrstuvwxyz'
S2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

def isprime(x):
	if x <= 1:
		return False
	if x in (2, 3):
		return True
	if x % 2 == 0:
		return False
	for i in range(3, int(sqrt(x)) + 1, 2):
		if x % i == 0:
			return False
	return True
for _ in range(int(inp())):
	(n, m) = mp()
	arr = lmp()
	barr = lmp()
	md = dd(int)
	for i in barr:
		md[i] = 1
	inds = {}
	for i in range(m):
		inds[barr[i]] = i
	c = 0
	chk = l1d(m)
	ans = 0
	pre = 0
	for i in range(m):
		if not chk[i]:
			for j in range(pre, n):
				if md[arr[j]]:
					chk[inds[arr[j]]] = 1
				if arr[j] == barr[i]:
					break
			ans += 2 * (j - c + 1) - 1
			pre = j
			c += 1
		else:
			ans += 1
			c += 1
	print(ans)


import sys
input = sys.stdin.buffer.readline
t = int(input())
for _ in range(t):
	(N, M) = map(int, input().split())
	A = list(map(int, input().split()))
	B = list(map(int, input().split()))
	idx_A = {}
	for i in range(N):
		idx_A[A[i]] = i + 1
	ans = 0
	j = 0
	for (i, b) in enumerate(B):
		if idx_A[b] > j:
			j = idx_A[b]
			ans += 2 * j - 1 - i * 2
		else:
			ans += 1
	print(ans)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	p = list(map(int, input().split()))
	send = list(map(int, input().split()))
	ans = 0
	sort = []
	start = 0
	pr = {}
	for i in range(n):
		pr[p[i]] = i
	t = 0
	m_s = 0
	for i in range(m):
		if pr[send[i]] > m_s:
			ans += (pr[send[i]] - i) * 2 + 1
			m_s = pr[send[i]]
		else:
			ans += 1
	print(ans)


t = int(input())
for ii in range(t):
	(n, m) = list(map(int, input().split()))
	a = [None] + list(map(int, input().split()))
	b = [None] + list(map(int, input().split()))
	bb = [None] * (n + 2)
	for i in range(1, m + 1):
		bb[b[i]] = i
	total = 0
	last_ind = n
	last_b = m
	for i in range(n, 0, -1):
		if bb[a[i]] is None:
			continue
		else:
			cur_ind = bb[a[i]]
			if i < cur_ind or last_b < cur_ind:
				continue
			total += 2 * (i - 1 - (cur_ind - 1)) + 1
			total += last_b - cur_ind
			last_b = cur_ind - 1
	print(total)


t = int(input())
for y in range(t):
	(n, m) = list(map(int, input().split()))
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	ind = [0 for i in range(n + 1)]
	for i in range(n):
		ind[a[i]] = i
	(mx, ans) = (-1, 0)
	for i in range(m):
		if ind[b[i]] > mx:
			mx = ind[b[i]]
			ans += 2 * (ind[b[i]] - i) + 1
		else:
			ans += 1
	print(ans)


t = int(input())
for i in range(t):
	nm = list(map(int, input().split()))
	n = nm[0]
	m = nm[1]
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	pos = [0] * (n + 1)
	for j in range(n):
		pos[a[j]] = j
	ans = 2 * pos[b[0]] + 1
	k = pos[b[0]]
	for j in range(1, len(b)):
		if pos[b[j]] < k:
			ans += 1
		else:
			ans += 2 * (pos[b[j]] - j) + 1
			k = pos[b[j]]
	print(ans)


for i in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	d = {}
	for j in range(n):
		d[a[j]] = j
	max1 = -1
	count = 0
	for j in range(m):
		if d[b[j]] > max1:
			count += 2 * (d[b[j]] - j) + 1
			max1 = d[b[j]]
		else:
			count += 1
	print(count)


test = int(input())
while test > 0:
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	seen = set()
	t = {}
	(i, j) = (0, 0)
	while j < m:
		if b[j] in seen:
			t[j] = 0
		else:
			while a[i] != b[j]:
				seen.add(a[i])
				i += 1
			t[j] = i - j
			seen.add(a[i])
			i += 1
		j += 1
	op = 0
	for i in t:
		op += t[i] * 2 + 1
	print(op)
	test -= 1


def optimal_stacking(gifts, specials):
	max_index = 0
	movt_count = 0
	for i in range(len(specials)):
		found = False
		for j in range(max_index, len(gifts)):
			if specials[i] == gifts[j]:
				movt_count += 2 * (j - i) + 1
				max_index = j
				found = True
				break
		if not found:
			movt_count += 1
	return movt_count
useless = int(input())
for i in range(useless):
	a = input()
	gifts = [int(i) for i in input().split()]
	specials = [int(i) for i in input().split()]
	print(optimal_stacking(gifts, specials))


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	memo = {}
	for i in range(n):
		memo[a[i]] = i
	max_num = -1
	cnt = 0
	ans = 0
	for i in range(m):
		if max_num < memo[b[i]]:
			ans += 2 * (memo[b[i]] - cnt) + 1
			max_num = memo[b[i]]
			cnt += 1
		else:
			ans += 1
			cnt += 1
	print(ans)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	l = {val: idx + 1 for (idx, val) in enumerate(map(int, input().split()))}
	(ans, curr, maxim) = (0, 1, 0)
	for i in map(int, input().split()):
		if l[i] > maxim:
			ans += 2 * (l[i] - curr) + 1
			maxim = l[i]
		else:
			ans += 1
		curr += 1
	print(ans)


n_cases = int(input().strip())
for _ in range(n_cases):
	(n, m) = list(map(int, input().strip().split()))
	a = list(map(int, input().strip().split()))
	b = list(map(int, input().strip().split()))
	wait_set = set()
	total = 0
	cursor = 0
	for b_m in b:
		if b_m in wait_set:
			total += 1
			wait_set.remove(b_m)
		else:
			i = a.index(b_m, cursor)
			total += 2 * (len(a[cursor:i]) + len(wait_set)) + 1
			wait_set.update(a[cursor:i])
			cursor = i + 1
	print(total)


import math
import copy
t = int(input())
for _ in range(t):
	(n, m) = [int(i) for i in input().split()]
	a = [int(i) for i in input().split()]
	b = [int(i) for i in input().split()]
	d = [0] * n
	for i in range(n):
		d[a[i] - 1] = i
	j = -1
	c = m
	for i in range(m):
		if d[b[i] - 1] > j:
			c += 2 * (d[b[i] - 1] - i)
			j = d[b[i] - 1]
	print(c)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	ans = 0
	j = 0
	lenb = len(b)
	prev = 0
	removed = 0
	d = {}
	while j < lenb:
		for i in range(prev, len(a)):
			if a[i] != b[j]:
				d[a[i]] = 1
			else:
				ans += 2 * (i - removed) + 1
				removed += 1
				break
		prev = i + 1
		j += 1
		while j < lenb:
			if d.get(b[j]):
				ans += 1
				j += 1
				removed += 1
			else:
				break
	print(ans)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	arr = list(map(int, input().split()))
	brr = list(map(int, input().split()))
	indi = [0] * (n + 1)
	for i in range(n):
		indi[arr[i]] = i + 1
	right = -1
	ans = 0
	for i in range(m):
		if indi[brr[i]] > right:
			ans += (indi[brr[i]] - i - 1) * 2 + 1
			right = indi[brr[i]]
		else:
			ans += 1
	print(ans)


for t in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	solved = set()
	b_set = set(b)
	pos = 0
	time = 0
	for i in range(len(b)):
		if b[i] in solved:
			time += 1
			continue
		for j in range(pos, len(a)):
			if a[j] == b[i]:
				time += 2 * (j - i) + 1
				pos = j
				break
			elif a[j] in b_set:
				solved.add(a[j])
	print(time)


t = int(input())
for i in ' ' * t:
	(n, m) = map(int, input().split())
	L1 = list(map(int, input().split()))
	L2 = list(map(int, input().split()))
	L3 = [0] * len(L1) + [0]
	L4 = [0] * len(L2) + [0]
	for j in range(len(L2)):
		L3[L2[j]] = j + 1
	for j in range(len(L1)):
		if L3[L1[j]] != 0:
			L4[L3[L1[j]]] = j + 1
	L4 = L4[1:]
	mx = max(L4)
	c = 0
	mxx = 0
	for i in range(len(L4)):
		k = L4[i] - i
		if L4[i] >= mxx:
			mxx = L4[i]
			c += k * 2 - 1
		else:
			c += 1
	print(c)


import sys
input = sys.stdin.readline
t = int(input())
while t > 0:
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	vt = {}
	for i in range(len(a)):
		vt[a[i]] = i
	sum = 0
	max_i = -1
	for i in range(len(b)):
		max_i = max(vt[b[i]], max_i)
		if vt[b[i]] < max_i:
			sum += 1
		else:
			sum += 2 * (vt[b[i]] - i) + 1
	print(sum)
	t -= 1


for test in range(int(input())):
	arr1 = list(map(int, input().split()))
	n = arr1[0]
	m = arr1[1]
	arr1 = list(map(int, input().split()))
	arr2 = list(map(int, input().split()))
	dicti = {arr1[i]: i for i in range(n)}
	ans = 0
	ans += 2 * dicti[arr2[0]] + 1
	farthest = dicti[arr2[0]]
	for i in range(1, m):
		if dicti[arr2[i]] < farthest:
			ans += 1
		else:
			ans += 2 * (dicti[arr2[i]] - i) + 1
			farthest = dicti[arr2[i]]
	print(ans)


from sys import stdin
inp = stdin.readline
t = int(inp())
while t:
	t -= 1
	(n, m) = map(int, inp().split())
	a = list(map(int, inp().split()))
	b = list(map(int, inp().split()))
	a_index = [0] * (n + 1)
	ans = 0
	for i in range(n):
		a_index[a[i]] = i
	cur_max = 0
	for j in range(m):
		if a_index[b[j]] > cur_max:
			ans += 2 * (a_index[b[j]] - j)
			cur_max = a_index[b[j]]
		ans += 1
	print(ans)


from collections import defaultdict
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	d = defaultdict(int)
	for i in range(n):
		d[a[i]] = i
	s = set()
	r = 0
	curr = 0
	for i in range(m):
		if d[b[i]] < curr:
			r += 1
		else:
			r += 2 * (d[b[i]] - i) + 1
			curr = d[b[i]]
	print(r)


t = int(input())
for i in range(t):
	(n, m) = [int(x) for x in input().split()]
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	order = []
	for j in range(len(a) + 5):
		order.append(0)
	ans = 0
	bottom = 0
	for j in range(len(a)):
		order[a[j]] = j
	for j in range(len(b)):
		if order[b[j]] > bottom:
			ans += 2 * (order[b[j]] - j) + 1
			bottom = order[b[j]]
		else:
			ans += 1
	print(ans)


import sys
input = sys.stdin.readline
t = int(input())
for i in range(t):
	(n, m) = map(int, input().split())
	first = [int(i) for i in input().split()]
	gifts = [int(i) for i in input().split()]
	count = 0
	index = [0] * (max(first) + 1)
	for i in range(n):
		index[first[i]] = i
	sum_ = 0
	tmp = 0
	for i in range(m):
		indoo = index[gifts[i]]
		if indoo >= tmp:
			tmp = indoo
			sum_ += 2 * (indoo - count) + 1
			count += 1
		else:
			count += 1
			sum_ += 1
	print(sum_)


t = int(input())
while t > 0:
	(n, m) = [int(ele) for ele in input().split()]
	a = [int(ele) for ele in input().split()]
	b = [int(ele) for ele in input().split()]
	count = 0
	c = 0
	mem = {}
	for i in range(n):
		mem[a[i]] = i
	for i in range(m):
		if i == 0:
			maxi = mem[b[i]]
			count += 2 * mem[b[i]] + 1
			c += 1
		elif mem[b[i]] < maxi:
			count += 1
			c += 1
		else:
			count += 2 * (mem[b[i]] - c) + 1
			maxi = mem[b[i]]
			c += 1
	print(count)
	t -= 1


from sys import stdin
from collections import deque
input = stdin.readline
q = int(input())
for _ in range(q):
	(n, m) = map(int, input().split(' '))
	a = deque(map(int, input().split(' ')))
	b = list(map(int, input().split(' ')))
	s = set([])
	moves = 0
	actual = 0
	for i in range(m):
		if b[i] in s:
			moves += 1
			s.remove(b[i])
			actual -= 1
		else:
			k = a.index(b[i])
			moves += 2 * (k + actual) + 1
			for i in range(k):
				s.add(a.popleft())
				actual += 1
			a.popleft()
	print(moves)


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	(n, m) = [int(x) for x in input().strip().split()]
	a = {int(x): i for (i, x) in enumerate(input().strip().split())}
	b = [int(x) for x in input().strip().split()]
	ans = 0
	s = 0
	done = 0
	for bb in b:
		i = a[bb]
		if s > i:
			ans += 1
			done += 1
		else:
			s = i
			ans += 2 * (i - done) + 1
			done += 1
	print(ans)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	result = 0
	index = 0
	numProcessed = 0
	toSent = set(b)
	processed = set()
	for val in b:
		if val in processed:
			numProcessed += 1
			result += 1
		else:
			while a[index] != val:
				if a[index] in toSent:
					processed.add(a[index])
				index += 1
			result += (index - numProcessed) * 2 + 1
			numProcessed += 1
	print(result)


for _ in range(int(input())):
	(n, m) = map(int, input().split(' '))
	data = [0] * (n + 1)
	a = list(map(int, input().split(' ')))
	b = list(map(int, input().split(' ')))
	for i in range(n):
		data[a[i]] = i
	forwards = [0] * m
	for i in range(m):
		forwards[i] = data[b[i]]
	array = [0] * m
	max_value = 0
	result = 0
	for i in range(m):
		if max_value < forwards[i]:
			array[i] = forwards[i] - i
			max_value = forwards[i]
		else:
			array[i] = 0
	for i in array:
		result += 2 * i + 1
	print(result)


T = int(input())
for _ in range(T):
	(n, m) = map(int, input().split())
	stack = list(map(int, input().split()))[::-1]
	b = list(map(int, input().split()))
	pre_true = [0] * (n + 1)
	for i in b:
		pre_true[i] = 1
	rem = set()
	ans1 = 0
	ans = 0
	for i in b:
		if i in rem:
			ans += 1
			rem.remove(i)
		else:
			ans1 = 0
			val = -1
			while val != i:
				val = stack.pop()
				if val != i:
					rem.add(val)
			ans += 2 * len(rem) + 1
	print(ans)


for t in range(int(input())):
	(n, m) = [*map(int, input().split())]
	a = [*map(int, input().split())]
	b = [*map(int, input().split())]
	mp = {v: i for (i, v) in enumerate(a)}
	m_ind = 0
	res = 0
	rmv_cnt = 0
	for e in b:
		if mp[e] <= m_ind:
			res += 1
		else:
			res += 2 * (mp[e] - rmv_cnt) + 1
			m_ind = mp[e]
		rmv_cnt += 1
	print(res)


import os
import sys
from io import BytesIO, IOBase
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))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from collections import defaultdict
from bisect import bisect
from heapq import heapify, heappush as hp, heappop as pop
t = int(input())
for i in range(t):
	(n, m) = map(int, input().split())
	l1 = list(map(int, input().split()))
	l2 = list(map(int, input().split()))
	d = defaultdict(int)
	for j in range(n):
		d[l1[j]] = j
	j = 0
	ans = 0
	h = []
	heapify(h)
	while j < m:
		a = bisect(h, d[l2[j]])
		ans += 2 * (d[l2[j]] - a) + 1
		hp(h, d[l2[j]])
		b = l2[j]
		j += 1
		if j == m:
			break
		while d[l2[j]] < d[b]:
			ans += 1
			hp(h, d[l2[j]])
			j += 1
			if j == m:
				break
	print(ans)


test = int(input())
while test:
	test -= 1
	line = input()
	line = line.split()
	n = int(line[0])
	m = int(line[1])
	a = list()
	b = list()
	v = list()
	for i in range(n + 1):
		b += [0]
	line = input()
	line = line.split()
	for elem in line:
		a += [int(elem)]
	line = input()
	line = line.split()
	for elem in line:
		v += [int(elem)]
	poz = 0
	ans = 0
	for i in range(m):
		if b[v[i]] != 0:
			ans += 1
		else:
			while a[poz] != v[i]:
				b[a[poz]] = 1
				poz += 1
			ans += 2 * (poz - i) + 1
	print(ans)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	sb = set(b)
	idx = {}
	for i in range(len(a)):
		if a[i] in sb:
			idx[a[i]] = i
	vis = -1
	ans = 0
	b = b[::-1]
	baari = 0
	while b:
		rmv = b.pop()
		ind = idx[rmv]
		if ind <= vis:
			ans += 1
		else:
			ans += 2 * (ind - baari) + 1
			vis = ind
		baari += 1
	print(ans)


import sys
lines = sys.stdin.readlines()
T = int(lines[0].strip())
for t in range(T):
	[n, m] = list(map(lambda x: int(x), lines[3 * t + 1].strip().split(' ')))
	stack = list(map(lambda x: int(x), lines[3 * t + 2].strip().split(' ')))
	order = list(map(lambda x: int(x), lines[3 * t + 3].strip().split(' ')))
	numMap = {}
	for i in range(n):
		numMap[stack[i]] = i
	indices = [0] * m
	for i in range(m):
		indices[i] = numMap[order[i]]
	tempMax = -1
	res = 0
	startPos = -1
	for i in range(m):
		if indices[i] > tempMax:
			tempMax = indices[i]
			res += 2 * (tempMax - startPos) - 1
			startPos = i
		else:
			res += 1
			startPos += 1
	print(res)


import os
import sys
from io import BytesIO, IOBase
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))
input = lambda : sys.stdin.readline().rstrip('\r\n')
for j in range(int(input())):
	(n, m) = map(int, input().split())
	dict1 = {}
	pres = list(map(int, input().split()))
	send = list(map(int, input().split()))
	for s in range(n):
		dict1[pres[s]] = s
	maxsofar = 0
	time = 0
	depth = 0
	for s in range(m):
		if dict1[send[s]] < maxsofar:
			time += 1
		else:
			time += 2 * (dict1[send[s]] - depth) + 1
			maxsofar = dict1[send[s]]
		depth += 1
	print(time)


def main(argc, argv) -> {}:
	sync_with_stdio(false)
	cin.tie(0)
	cout.tie(0)
	n = 0
	m = 0
	t = 0
	t <<= cin
	while t or {}:
		t -= 1
		n <<= cin
		m <<= cin
		A = vector << int >> n
		A <<= cin
		B = vector << int >> m
		B <<= cin
		pos = vector << int >> n + 1
		i = 0
		while i < n or {}:
			pos[A[i]] = i
			i += 1
			{}
		digdepth = 0
		time = 0
		j = 0
		while j < m or {}:
			if pos[B[j]] > digdepth or {}:
				digdepth = pos[B[j]]
				time += 2 * (digdepth - j)
				{}
			time += 1
			j += 1
			{}
		cout << time << endl
		{}
	return 0
	{}
import base64
exec(base64.b64decode(b'cHkyID0gcm91bmQoMC41KQoKaWYgcHkyOgogICAgZnJvbSBmdXR1cmVfYnVpbHRpbnMgaW1wb3J0IGFzY2lpLCBmaWx0ZXIsIGhleCwgbWFwLCBvY3QsIHppcAogICAgcmFuZ2UgPSB4cmFuZ2UKCmRlZiBzeW5jX3dpdGhfc3RkaW8oYik6CiAgICBpZiBiOiByZXR1cm4KICAgIGltcG9ydCBvcywgc3lzCiAgICBmcm9tIGlvIGltcG9ydCBCeXRlc0lPLCBJT0Jhc2UKICAgIAogICAgIyBGYXN0SU8gZm9yIFB5UHkyIGFuZCBQeVB5MyAod29ya3Mgd2l0aCBpbnRlcmFjdGl2ZSkgYnkgUGFqZW5lZ29kCiAgICBjbGFzcyBGYXN0SShvYmplY3QpOgogICAgICAgIGRlZiBfX2luaXRfXyhzZWxmLCBmZD0wLCBidWZmZXJzaXplPTIqKjE0KToKICAgICAgICAgICAgc2VsZi5zdHJlYW0gPSBzdHJlYW0gPSBCeXRlc0lPKCk7IHNlbGYuYnVmZW5kbCA9IDAKICAgICAgICAgICAgZGVmIHJlYWQyYnVmZmVyKCk6CiAgICAgICAgICAgICAgICBzID0gb3MucmVhZChmZCwgYnVmZmVyc2l6ZSArIG9zLmZzdGF0KGZkKS5zdF9zaXplKTsgcG9zID0gc3RyZWFtLnRlbGwoKQogICAgICAgICAgICAgICAgc3RyZWFtLnNlZWsoMCwyKTsgc3RyZWFtLndyaXRlKHMpOyBzdHJlYW0uc2Vlayhwb3MpOyByZXR1cm4gcwogICAgICAgICAgICBzZWxmLnJlYWQyYnVmZmVyID0gcmVhZDJidWZmZXIKICAgICAgICAjIFJlYWQgZW50aXJlIGlucHV0CiAgICAgICAgZGVmIHJlYWQoc2VsZik6CiAgICAgICAgICAgIHdoaWxlIHNlbGYucmVhZDJidWZmZXIoKTogcGFzcwogICAgICAgICAgICByZXR1cm4gc2VsZi5zdHJlYW0ucmVhZCgpIGlmIHNlbGYuc3RyZWFtLnRlbGwoKSBlbHNlIHNlbGYuc3RyZWFtLmdldHZhbHVlKCkKICAgICAgICBkZWYgcmVhZGxpbmUoc2VsZik6CiAgICAgICAgICAgIHdoaWxlIHNlbGYuYnVmZW5kbCA9PSAwOiBzID0gc2VsZi5yZWFkMmJ1ZmZlcigpOyBzZWxmLmJ1ZmVuZGwgKz0gcy5jb3VudChiIlxuIikgKyAobm90IHMpCiAgICAgICAgICAgIHNlbGYuYnVmZW5kbCAtPSAxOyByZXR1cm4gc2VsZi5zdHJlYW0ucmVhZGxpbmUoKQogICAgICAgIGRlZiBpbnB1dChzZWxmKTogcmV0dXJuIHNlbGYucmVhZGxpbmUoKS5yc3RyaXAoYidcclxuJykKICAgICAgICAKICAgICAgICAjIFJlYWQgYWxsIHJlbWFpbmluZyBpbnRlZ2VycywgdHlwZSBpcyBnaXZlbiBieSBvcHRpb25hbCBhcmd1bWVudAogICAgICAgIGRlZiByZWFkbnVtYmVycyhzZWxmLCB6ZXJvPTApOgogICAgICAgICAgICBjb252ID0gb3JkIGlmIHB5MiBlbHNlIGxhbWJkYSB4OngKICAgICAgICAgICAgQSA9IFtdOyBudW1iID0gemVybzsgc2lnbiA9IDE7IGMgPSBiIi0iWzBdCiAgICAgICAgICAgIGZvciBjIGluIHNlbGYucmVhZCgpOgogICAgICAgICAgICAgICAgaWYgYyA+PSBiIjAiWzBdOiBudW1iID0gMTAgKiBudW1iICsgY29udihjKSAtIDQ4CiAgICAgICAgICAgICAgICBlbGlmIGMgPT0gYiItIlswXTogc2lnbiA9IC0xCiAgICAgICAgICAgICAgICBlbGlmIGMgIT0gYiJcciJbMF06IEEuYXBwZW5kKHNpZ24qbnVtYik7IG51bWIgPSB6ZXJvOyBzaWduID0gMQogICAgICAgICAgICBpZiBjID49IGIiMCJbMF06IEEuYXBwZW5kKHNpZ24qbnVtYikKICAgICAgICAgICAgcmV0dXJuIEEKICAgIAogICAgY2xhc3MgRmFzdE8oSU9CYXNlKToKICAgICAgICBkZWYgX19pbml0X18oc2VsZiwgZmQ9MSk6CiAgICAgICAgICAgIHN0cmVhbSA9IEJ5dGVzSU8oKQogICAgICAgICAgICBzZWxmLmZsdXNoID0gbGFtYmRhOiBvcy53cml0ZSgxLCBzdHJlYW0uZ2V0dmFsdWUoKSkgYW5kIG5vdCBzdHJlYW0udHJ1bmNhdGUoMCkgYW5kIHN0cmVhbS5zZWVrKDApCiAgICAgICAgICAgIHNlbGYud3JpdGUgPSBzdHJlYW0ud3JpdGUgaWYgcHkyIGVsc2UgbGFtYmRhIHM6IHN0cmVhbS53cml0ZShzLmVuY29kZSgpKQogICAgCiAgICBzeXMuc3RkaW4sIHN5cy5zdGRvdXQgPSBGYXN0SSgpLCBGYXN0TygpCiAgICBnbG9iYWwgaW5wdXQKICAgIGlucHV0ID0gc3lzLnN0ZGluLmlucHV0CgoKaW1wb3J0IHN5cwoKY2xhc3Mgb3N0cmVhbToKICAgIGRlZiBfX2xzaGlmdF9fKHNlbGYsYSk6CiAgICAgICAgaWYgYSA9PSBlbmRsOgogICAgICAgICAgICBzeXMuc3Rkb3V0LndyaXRlKCJcbiIpCiAgICAgICAgICAgIHN5cy5zdGRvdXQuZmx1c2goKQogICAgICAgIGVsc2U6CiAgICAgICAgICAgIHN5cy5zdGRvdXQud3JpdGUoc3RyKGEpKQogICAgICAgIHJldHVybiBzZWxmCiAgICBkZWYgdGllKHNlbGYsIHZhbCk6cGFzcwpjb3V0ID0gb3N0cmVhbSgpCmVuZGwgPSBvYmplY3QoKQoKY2xhc3MgaXN0cmVhbToKICAgIHRpZWR0byA9IGNvdXQKICAgIGlucCA9IE5vbmUKICAgIGRlZiBfX3Jsc2hpZnRfXyhhLGIpOgogICAgICAgIGlmIGEudGllZHRvID09IGNvdXQ6CiAgICAgICAgICAgIHN5cy5zdGRvdXQuZmx1c2goKQogICAgICAgIGlmIHR5cGUoYik9PXR1cGxlIG9yIHR5cGUoYik9PWxpc3Q6CiAgICAgICAgICAgIHJldHVybiB0eXBlKGIpKHR5cGUoYykoYS5nZXQoKSkgZm9yIGMgaW4gYikKICAgICAgICByZXR1cm4gdHlwZShiKShhLmdldCgpKQogICAgZGVmIHRpZShzZWxmLCB2YWwpOgogICAgICAgIHNlbGYudGllZHRvID0gdmFsCiAgICBkZWYgZ2V0KGEpOgogICAgICAgIHdoaWxlIG5vdCBhLmlucDoKICAgICAgICAgICAgYS5pbnAgPSBzeXMuc3RkaW4ucmVhZGxpbmUoKS5zcGxpdCgpWzo6LTFdCiAgICAgICAgcmV0dXJuIGEuaW5wLnBvcCgpCmNpbiA9IGlzdHJlYW0oKQoKY2xhc3MgVmVjdG9yOgogICAgZGVmIF9fbHNoaWZ0X18oc2VsZiwgb3RoZXIpOgogICAgICAgIHNlbGYudHlwZSA9IG90aGVyCiAgICAgICAgcmV0dXJuIHNlbGYKICAgIGRlZiBfX3JzaGlmdF9fKHNlbGYsIG90aGVyKToKICAgICAgICBpZiB0eXBlKG90aGVyKSA9PSB0dXBsZToKICAgICAgICAgICAgcmV0dXJuIFtzZWxmLnR5cGUob3RoZXJbMV0pXSpvdGhlclswXQogICAgICAgIGVsc2U6CiAgICAgICAgICAgIHJldHVybiBbc2VsZi50eXBlKCldKm90aGVyCnZlY3RvciA9IFZlY3RvcigpCg=='))
false = False
true = True
main(len(sys.argv), sys.argv)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	(mp, id, cnt) = ({}, -1, 0)
	(v, w) = (list(map(int, input().split())), list(map(int, input().split())))
	for i in range(n):
		mp[v[i]] = i
	for i in range(m):
		x = mp[w[i]]
		if x > id:
			cnt += 2 * (x - i) + 1
			id = x
		else:
			cnt += 1
		cnt
	print(cnt)


t = int(input())
while t > 0:
	t -= 1
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	time = 0
	d_a = {}
	d_b = {}
	for i in range(n):
		d_a[a[i]] = i
	for i in range(m):
		d_b[b[i]] = i
	cur_max = d_a[b[0]]
	time += 2 * cur_max + 1
	for i in range(1, m):
		if d_a[b[i]] < cur_max:
			time += 1
		else:
			cur_max = d_a[b[i]]
			time += 2 * (d_a[b[i]] - i) + 1
	print(time)


t = int(input())
while t > 0:
	t -= 1
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	v = []
	for i in range(n + 1):
		v.append(0)
	l = 0
	r = 0
	prev = 0
	c = 0
	while l < m:
		x = b[l]
		if v[x]:
			c += 1
		else:
			while x != a[r]:
				v[a[r]] = 1
				r += 1
			v[x] = 1
			c += 2 * (r - l) + 1
		l += 1
		prev = r
	print(c)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	steps = 0
	ptr = 0
	prev = -1
	need = [False] * (n + 1)
	for c in b:
		need[c] = True
	sent = 0
	for i in range(m):
		if need[b[i]]:
			while ptr < n and b[i] != a[ptr]:
				if need[a[ptr]]:
					need[a[ptr]] = False
				ptr += 1
			steps += 2 * (ptr - sent)
			ptr += 1
		steps += 1
		sent += 1
	print(steps)


import collections
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	an = list(map(int, input().split()))
	am = list(map(int, input().split()))
	s = [0] * (n + 1)
	ans = 0
	i = 0
	ln = 0
	for (j, aj) in enumerate(am):
		if s[aj] == 1:
			ans += 1
		else:
			while s[aj] == 0:
				s[an[i]] = 1
				i += 1
			ans += 2 * (i - j - 1) + 1
	print(ans)


T = int(input())
for t in range(T):
	(n, m) = map(int, input().split())
	al = list(map(int, input().split()))
	bl = list(map(int, input().split()))
	ind = [0] * (n + 1)
	for (i, el) in enumerate(al):
		ind[el] = i
	sub = 0
	marked = 0
	cost = 0
	for (i, el) in enumerate(bl):
		idx = ind[el]
		if idx < marked:
			cost += 1
		else:
			cost += 2 * (idx - sub) + 1
			marked = idx
		sub += 1
	print(cost)


import os
import sys
from io import BytesIO, IOBase

def solution(arr, brr, n, m):
	pos = [0] * (n + 1)
	last_gift = -1
	arr.insert(0, 0)
	brr.insert(0, 0)
	for i in range(1, n + 1):
		pos[arr[i]] = i
	res = 0
	taken = 0
	for i in range(1, m + 1):
		if pos[brr[i]] > last_gift:
			res += 2 * (pos[brr[i]] - taken - 1) + 1
			last_gift = pos[brr[i]]
		else:
			res += 1
		taken += 1
	write(res)

def main():
	for _ in range(r_int()):
		(n, m) = r_array()
		arr = r_array()
		brr = r_array()
		solution(arr, brr, n, m)
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 input():
	return sys.stdin.readline().rstrip('\r\n')

def write(*args, end='\n'):
	for x in args:
		sys.stdout.write(str(x) + ' ')
	sys.stdout.write(end)

def r_array():
	return [int(x) for x in input().split()]

def r_int():
	return int(input())
main()


import sys
import math
import heapq
import collections

def inputnum():
	return int(input())

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

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

def inputstring():
	return [x for x in input()]

def inputstringnum():
	return [ord(x) - ord('a') for x in input()]

def inputmatrixchar(rows):
	arr2d = [[j for j in input().strip()] for i in range(rows)]
	return arr2d

def inputmatrixint(rows):
	arr2d = []
	for _ in range(rows):
		arr2d.append([int(i) for i in input().split()])
	return arr2d
t = int(input())
for q in range(t):
	(n, m) = inputnums()
	a = inputlist()
	b = inputlist()
	c = [0] * (n + 1)
	for i in range(n):
		c[a[i]] = i
	big = 0
	ans = 0
	for i in range(m):
		if c[b[i]] > big:
			ans += 2 * (c[b[i]] - i)
			big = c[b[i]]
	print(ans + m)


import math
t = int(input())
for i in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	present_order = [None for i in range(n + 1)]
	for i in range(len(b)):
		present_order[b[i]] = i
	min_present_seen = math.inf
	total_time = 0
	for i in range(len(a) - 1, -1, -1):
		if present_order[a[i]] != None:
			if present_order[a[i]] < min_present_seen:
				total_time += 2 * (i - present_order[a[i]]) + 1
			else:
				total_time += 1
			min_present_seen = min(min_present_seen, present_order[a[i]])
	print(total_time)


number = int(input())
for i in range(0, number):
	numbers = input()
	numberss = numbers.split()
	numbersss = list(map(int, numberss))
	n = numbersss[0]
	m = numbersss[1]
	ais = input().split()
	aiss = list(map(int, ais))
	aissmap = {}
	for i in range(0, n):
		aissmap[aiss[i]] = i
	bis = input().split()
	biss = list(map(int, bis))
	sortedindex = -1
	time = 0
	for i in range(0, m):
		j = biss[i]
		index1 = aissmap[j]
		if index1 < sortedindex:
			time = time + 1
		else:
			time = time + (index1 - i) * 2 + 1
			sortedindex = index1
			if sortedindex == n - 1:
				print(time + m - i - 1)
				break
		if i == m - 1:
			print(time)


T = int(input())
for t in range(T):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	for i in range(n):
		a[i] -= 1
	for j in range(m):
		b[j] -= 1
	nummap = [0 for i in range(n)]
	for i in range(n):
		nummap[a[i]] = i
	b = [nummap[b[i]] for i in range(m)]
	largest = -1
	res = 0
	for i in range(m):
		if b[i] >= largest:
			res += 2 * (b[i] - i) + 1
			largest = b[i]
		else:
			res += 1
	print(res)


t = int(input())
for q in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	sb = set(b)
	k = 0
	j = 0
	ans = 0
	c = 0
	i = 0
	while i < n:
		if j < m:
			if b[j] in sb:
				if a[i] == b[j]:
					ans += 2 * k + 1
					j += 1
				else:
					if a[i] in sb:
						ans += 1
						sb.remove(a[i])
					k += 1
			else:
				j += 1
				i -= 1
				k -= 1
		else:
			break
		i += 1
	print(ans)


from math import sqrt, ceil

def ii():
	return int(input())

def si():
	return input()

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

def li():
	return list(mi())
t = ii()
while t:
	t -= 1
	(n, m) = mi()
	a = li()
	b = li()
	m1 = {}
	k = 0
	sum = 0
	for i in range(n):
		m1[a[i]] = i
	for i in range(m):
		k = max(k, m1[b[i]])
		if m1[b[i]] < k:
			sum += 1
		else:
			s = m1[b[i]] - i
			sum += 2 * s + 1
	print(sum)


t = int(input())
for _ in range(t):
	xyz = [int(x) for x in input().split()]
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	c = set()
	j = 0
	cost = 0
	for bi in b:
		if bi in c:
			cost += 1
			c.remove(bi)
		else:
			while j < len(a):
				if a[j] == bi:
					cost += 2 * len(c) + 1
					j += 1
					break
				else:
					c.add(a[j])
					j += 1
	print(cost)


n = int(input())
for i in range(n):
	ch = input()
	L = [int(i) for i in ch.split()]
	n = L[0]
	m = L[1]
	ch = input()
	L1 = [int(i) for i in ch.split()]
	ch = input()
	L2 = [int(i) for i in ch.split()]
	maxx = -1
	somm = 0
	tab_ind = [-1] * (n + 1)
	for i in range(n):
		tab_ind[L1[i]] = i
	for j in range(len(L2)):
		ind = tab_ind[L2[j]]
		if ind > maxx:
			somm += 2 * (ind - j) + 1
			maxx = ind
		else:
			somm += 1
	print(somm)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	ar = list(map(int, input().split()))
	br = list(map(int, input().split()))
	dic = {}
	for i in range(m):
		dic[br[i]] = 0
	for j in range(n):
		if dic.get(ar[j], -1) == -1:
			continue
		else:
			dic[ar[j]] = j
	maxind = 0
	time = 0
	count = 0
	for i in br:
		if dic[i] > maxind:
			time += abs(dic[i] - count) * 2 + 1
			count += 1
			maxind = dic[i]
		elif dic[i] == maxind:
			time += 1
			count += 1
		else:
			time += 1
			count += 1
	print(time)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	arr = list(map(int, input().split()))
	brr = list(map(int, input().split()))
	ans = 0
	cnt = 0
	track = {}
	rem = 0
	j = 0
	for i in arr:
		track[i] = j
		j += 1
	for i in range(len(brr)):
		e = brr[i]
		k = track[e]
		if k <= cnt:
			ans += 1
			rem += 1
		else:
			cnt = k
			k = k - rem
			ans += 2 * k + 1
			rem += 1
	print(ans)


q = int(input())
for i in range(q):
	input()
	a = [int(i) for i in input().split()]
	b = [int(i) for i in input().split()]
	se = set()
	l = 0
	ans = 0
	for i in range(len(a)):
		se.add(a[i])
		if l == len(b):
			break
		if a[i] == b[l]:
			ans += (i - l) * 2 + 1
			l += 1
		if l == len(b):
			break
		while b[l] in se:
			l += 1
			ans += 1
			if l == len(b):
				break
	ans += len(b) - l
	print(ans)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	A = list(map(int, input().split()))
	B = list(map(int, input().split()))
	pos = [0] * (max(A) + 1)
	for i in range(n):
		pos[A[i]] = i
	ans = pos[B[0]] * 2 + 1
	b = pos[B[0]]
	D = 1
	d = 1
	for i in range(1, m):
		if pos[B[i]] <= b:
			ans += 1
			D += 1
		else:
			ans += 2 * (pos[B[i]] - D) + 1
			b = pos[B[i]]
			D += 1
			d = 1
	print(ans)


t = int(input())
for i in range(t):
	(n, m) = input().split(' ')
	n = int(n)
	m = int(m)
	arr_a = list(map(lambda x: int(x), input().split(' ')))
	arr_b = list(map(lambda x: int(x), input().split(' ')))
	arr = [[1000000, -1] for j in range(n)]
	for j in range(n):
		arr[arr_a[j] - 1][1] = j
	for j in range(m):
		arr[arr_b[j] - 1][0] = j
	arr.sort()
	val = arr[0][1] * 2 + 1
	count = 1
	maximum = arr[0][1]
	j = 1
	while j <= m - 1:
		if arr[j][1] < maximum:
			val += 1
			count += 1
		else:
			maximum = arr[j][1]
			val += (arr[j][1] - count) * 2 + 1
			count += 1
		j += 1
	print(val)


import sys
I = sys.stdin.readline
ans = ''
for _ in range(int(I())):
	(n, m) = map(int, I().split())
	a = list(map(int, I().split()))
	b = list(map(int, I().split()))
	d = dict()
	for i in range(n):
		d[a[i]] = i
	max_ind = -1
	time = 0
	que = 0
	for i in b:
		ind = d[i]
		if ind < max_ind:
			time += 1
		else:
			max_ind = ind
			time += (ind - que) * 2 + 1
		que += 1
	ans += str(time) + '\n'
print(ans)


for i in range(int(input())):
	(n, m) = map(int, input().split())
	stack = list(map(int, input().split()))
	presents = list(map(int, input().split()))
	a = [0] * (10 ** 5 + 1)
	for i in range(n):
		a[stack[i]] = i
	upto = 0
	ans = 0
	for i in range(m):
		if a[presents[i]] <= upto:
			ans += 1
		else:
			ans += 2 * (a[presents[i]] - i) + 1
		upto = max(upto, a[presents[i]])
	print(ans)


import sys
import collections
from collections import Counter
import itertools
import math
import timeit
input = sys.stdin.readline

def sieve(n):
	if n < 2:
		return list()
	prime = [True for _ in range(n + 1)]
	p = 3
	while p * p <= n:
		if prime[p]:
			for i in range(p * 2, n + 1, p):
				prime[i] = False
		p += 2
	r = [2]
	for p in range(3, n + 1, 2):
		if prime[p]:
			r.append(p)
	return r

def divs(n, start=1):
	divisors = []
	for i in range(start, int(math.sqrt(n) + 1)):
		if n % i == 0:
			if n / i == i:
				divisors.append(i)
			else:
				divisors.extend([i, n // i])
	return divisors

def divn(n, primes):
	divs_number = 1
	for i in primes:
		if n == 1:
			return divs_number
		t = 1
		while n % i == 0:
			t += 1
			n //= i
		divs_number *= t

def flin(d, x, default=-1):
	left = right = -1
	for i in range(len(d)):
		if d[i] == x:
			if left == -1:
				left = i
			right = i
	if left == -1:
		return (default, default)
	else:
		return (left, right)

def ceil(n, k):
	return n // k + (n % k != 0)

def ii():
	return int(input())

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

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

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

def prr(a, sep=' '):
	print(sep.join(map(str, a)))

def dd():
	return collections.defaultdict(int)

def ddl():
	return collections.defaultdict(list)
t = ii()
for _ in range(t):
	(n, m) = mi()
	a = li()
	b = li()
	pos = [0] * (n + 1)
	for i in range(n):
		pos[a[i]] = i
	q = res = 0
	for i in range(m):
		res += 1 if pos[b[i]] < q else 2 * (pos[b[i]] - i) + 1
		q = max(q, pos[b[i]])
	print(res)


for _ in range(int(input())):
	(a, b) = [int(x) for x in input().split()]
	c = input().split()
	d = input().split()
	dc = {}
	for i in range(a):
		if c[i] not in dc:
			dc[c[i]] = 0
		dc[c[i]] = i
	s = ans = 0
	for i in range(b):
		t = dc[d[i]]
		if t > s:
			ans += 2 * (t - i) + 1
			s = t
		else:
			ans += 1
	print(ans)


for ttt in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	for i in range(n):
		a[i] -= 1
	for i in range(m):
		b[i] -= 1
	d = {}
	for i in range(n):
		d[a[i]] = i
	last = -1
	ans = m
	for i in range(m):
		if d[b[i]] > last:
			ans += 2 * (d[b[i]] - i)
			last = d[b[i]]
	print(ans)


import collections
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	new = set()
	h = 0
	t = 0
	for j in range(len(b)):
		if b[j] in new:
			t += 1
			continue
		while b[j] not in new:
			new.add(a[h])
			h += 1
		t += 2 * (h - j - 1) + 1
	print(t)


import sys

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

def list2d(a, b, c):
	return [[c] * b for i in range(a)]

def list3d(a, b, c, d):
	return [[[d] * c for j in range(b)] for i in range(a)]

def list4d(a, b, c, d, e):
	return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]

def ceil(x, y=1):
	return int(-(-x // y))

def INT():
	return int(input())

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

def LIST(N=None):
	return list(MAP()) if N is None else [INT() for i in range(N)]

def Yes():
	print('Yes')

def No():
	print('No')

def YES():
	print('YES')

def NO():
	print('NO')
sys.setrecursionlimit(10 ** 9)
INF = 10 ** 18
MOD = 10 ** 9 + 7
for _ in range(INT()):
	(N, M) = MAP()
	A = LIST()
	B = LIST()
	A2 = [-1] * (N + 1)
	for (i, a) in enumerate(A):
		A2[a] = i
	depth = cnt = 0
	for (i, b) in enumerate(B):
		a = A2[b]
		if a < depth:
			cnt += 1
		else:
			cnt += (a - i) * 2 + 1
			depth = a + 1
	print(cnt)


for t in range(int(input())):
	(n, m) = [int(x) for x in input().split()]
	a = [int(x) - 1 for x in input().split()]
	b = [int(x) - 1 for x in input().split()]
	l = [0] * n
	for i in range(len(a)):
		l[a[i]] = i
	res = 0
	ma = 0
	for i in range(len(b)):
		if l[b[i]] <= ma:
			res += 1
		else:
			res += 2 * (l[b[i]] - i) + 1
			ma = l[b[i]]
	print(res)


test_cases = int(input())
for _ in range(test_cases):
	(n, m) = map(int, input().split())
	all_presents = list(map(int, input().split()))
	presents_to_send = list(map(int, input().split()))
	presents_by_index = {all_presents[index]: index for index in range(len(all_presents))}
	operations_so_far = 0
	furthest_index = -1
	for index in range(len(presents_to_send)):
		present_to_send = presents_to_send[index]
		current_index = presents_by_index[present_to_send]
		if current_index <= furthest_index:
			operations_so_far += 1
		else:
			furthest_index = current_index
			presents_to_pop = current_index - index
			operations_so_far += presents_to_pop * 2 + 1
	print(operations_so_far)


t = int(input())
for _ in range(t):
	arr = [int(i) for i in input().split()]
	n = arr[0]
	m = arr[1]
	a = [int(i) for i in input().split()]
	b = [int(i) for i in input().split()]
	atoindex = {}
	for (index, num) in enumerate(a):
		atoindex[num] = index
	ans = 0
	maxIndex = 0
	for (j, num) in enumerate(b):
		currIndex = atoindex[num]
		if currIndex > maxIndex:
			maxIndex = currIndex
			ans = ans + 2 * (currIndex - j) + 1
		else:
			ans = ans + 1
	print(ans)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = [x - 1 for x in list(map(int, input().split()))]
	b = [x - 1 for x in list(map(int, input().split()))]
	mp = {}
	cnt = m
	pos = -1
	for i in range(n):
		mp[a[i]] = i
	for i in range(m):
		if mp[b[i]] > pos:
			cnt += (mp[b[i]] - i) * 2
			pos = mp[b[i]]
	print(cnt)


t = int(input())
for i in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	d = dict()
	for i in range(len(a)):
		d[a[i]] = i
	b = list(map(int, input().split()))
	(c, md) = (0, -1)
	disp = 0
	for i in b:
		dpth = d[i]
		if dpth > md:
			md = dpth
			c += 1 + (dpth - disp) * 2
		else:
			c += 1
		disp += 1
	print(c)


I = input
for _ in range(int(I())):
	(n, m) = map(int, I().split())
	a = list(map(int, I().split(' ')))
	b = list(map(int, I().split(' ')))
	d = dict()
	for i in b:
		d[i] = 0
	c = 0
	i = 0
	j = 0
	while i < m:
		if d[b[i]] != 1:
			while j < n:
				if a[j] == b[i]:
					c += 2 * (j - i) + 1
					d[a[j]] = 1
					j += 1
					break
				if a[j] in d and d[a[j]] != 1:
					c += 1
					d[a[j]] = 1
				j += 1
		i += 1
	print(c)


t = int(input())
for j in range(t):
	arr = list(map(int, input().split()))
	n = arr[0]
	m = arr[1]
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	for i in range(n):
		a[i] -= 1
	for i in range(m):
		b[i] -= 1
	p = [0] * n
	for i in range(n):
		p[a[i]] = i
	l = -1
	f = m
	for i in range(m):
		if p[b[i]] > l:
			f += 2 * (p[b[i]] - i)
			l = p[b[i]]
	print(f)


from math import *
import os, sys
from bisect import *
from io import BytesIO
sys.setrecursionlimit(10 ** 9)
for i in range(int(input())):
	(n, m) = list(map(int, input().split()))
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	d = {}
	for i in range(n):
		d[a[i]] = i
	ans = 0
	mx = 0
	for i in range(m):
		if mx < d[b[i]]:
			ans += 2 * (d[b[i]] - i) + 1
			mx = d[b[i]]
		else:
			ans += 1
	print(ans)


for _ in range(int(input())):
	input()
	have = []
	for (i, elem) in enumerate(input().split()):
		have.append((i, int(elem) - 1))
	have.sort(key=lambda x: x[1])
	massive = list((int(i) - 1 for i in input().split()))
	counter = 0
	taken = 0
	maxx = -1
	for i in massive:
		if have[i][0] < maxx:
			counter += 1
		else:
			maxx = have[i][0]
			counter += 2 * (have[i][0] - taken) + 1
		taken += 1
	print(counter)


t = int(input())
for i in range(0, t):
	nm = [int(i) for i in input().split()]
	ais = [int(i) for i in input().split()]
	bis = [int(i) for i in input().split()]
	aimap = {}
	for (i, ai) in enumerate(ais):
		aimap[ai] = i
	mx = 0
	ans = 0
	for (j, bi) in enumerate(bis):
		if aimap[bi] > mx:
			mx = aimap[bi]
			ans += 2 * (mx - j) + 1
		else:
			ans += 1
	print(ans)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = [0] + list(map(int, input().split()))
	b = [0] + list(map(int, input().split()))
	pos = [0] * (n + 1)
	for i in range(1, n + 1):
		pos[a[i]] = i
	maxx = 0
	ans = 0
	for i in range(1, m + 1):
		if pos[b[i]] <= maxx:
			ans = ans + 1
		else:
			ans = ans + 2 * (pos[b[i]] - 1 - (i - 1)) + 1
			maxx = pos[b[i]]
	print(ans)


def ain():
	return map(int, input().split())
for _ in range(int(input())):
	(n, m) = ain()
	a = list(ain())
	b = list(ain())
	pos = {}
	for i in range(n):
		x = a[i]
		pos[x] = i
	exp = 0
	tot = 0
	c = 0
	for x in b:
		posn = pos[x]
		if posn > exp:
			tot += 2 * (posn - c) + 1
			exp = posn
		else:
			tot += 1
		c += 1
	print(tot)


t = int(input())
while t > 0:
	d = {}
	(n, m) = [int(i) for i in input().split()]
	arr = [int(i) for i in input().split()]
	arr1 = [int(i) for i in input().split()]
	for i in range(n):
		d[arr[i]] = i
	summ = 0
	end = 0
	for i in range(m):
		if d[arr1[i]] > end:
			end = d[arr1[i]]
			summ += 2 * (d[arr1[i]] - i) + 1
		else:
			summ += 1
	print(summ)
	t -= 1


for tc in range(int(input())):
	(n, m) = list(map(int, input().split()))
	al = list(map(int, input().split()))
	bl = list(map(int, input().split()))
	aidx = {}
	for (i, e) in enumerate(al):
		aidx[e] = i
	midx = -1
	res = 0
	for (i, e) in enumerate(bl):
		idx = aidx[e]
		if idx <= midx:
			res += 1
		else:
			res += 2 * (idx - i) + 1
		midx = max(midx, idx)
	print(res)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	A = [*map(int, input().split())]
	B = [*map(int, input().split())]
	P = [0] * (n + 1)
	O = [0] * m
	for i in range(n):
		P[A[i]] = i + 1
	for i in range(m):
		O[i] = P[B[i]]
	r = 0
	maxi = 0
	cont = 0
	for i in range(m):
		if O[i] > maxi:
			r += (O[i] - cont - 1) * 2 + 1
			cont += 1
			maxi = max(maxi, O[i])
		else:
			r += 1
			cont += 1
	print(r)


t = int(input())
answers = []
for ti in range(t):
	ints = list(map(int, input().split()))
	(n, m) = (ints[0], ints[1])
	stack = list(map(int, input().split()))
	stack.reverse()
	b = list(map(int, input().split()))
	time = 0
	cache = {}
	for i in range(len(b)):
		if b[i] in cache:
			time += 1
			cache.pop(b[i])
			continue
		p = stack.pop()
		while p != b[i]:
			cache[p] = 1
			p = stack.pop()
		time += 2 * len(cache) + 1
	answers.append(time)
for a in answers:
	print(a)


from sys import stdin, stdout
from math import *
for i in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	h = [0] * (n + 1)
	x = 0
	y = 0
	ans = 0
	st = 0
	while y < m:
		if h[b[y]] == 1:
			ans += 1
			y += 1
			st -= 1
		else:
			if a[x] == b[y]:
				ans += 2 * st + 1
				y += 1
			else:
				h[a[x]] = 1
				st += 1
			x += 1
	print(ans)


from operator import itemgetter
t = int(input())

def solve(n, m, a, b):
	pos = [0 for i in range(n + 1)]
	for i in range(n):
		pos[a[i]] = i
	lst = -1
	ans = 0
	for i in range(m):
		if pos[b[i]] > lst:
			ans += 1 + 2 * (pos[b[i]] - i)
			lst = pos[b[i]]
		else:
			ans += 1
	print(ans)
for i in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	solve(n, m, a, b)


for _ in range(int(input())):
	(A, B) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	place = {}
	for (i, x) in enumerate(a):
		place[x] = i
	MAX = -1
	ans = 0
	for (i, x) in enumerate(b):
		x = place[x]
		if x > MAX:
			MAX = x
			ans += 2 * (x - i) + 1
		else:
			ans += 1
	print(ans)


import sys
import math
from collections import Counter
import bisect
ma = lambda : map(int, input().split())
inp = lambda : [int(i) for i in input().split()]
s = sorted
for _ in range(int(input())):
	(n, m) = ma()
	a = inp()
	b = inp()
	bol = [0] * m
	has = {}
	has2 = {}
	for i in range(n):
		has[a[i]] = i
	for i in range(m):
		has2[b[i]] = i
	time = 0
	taken = 0
	maxi = 0
	for i in range(m):
		if bol[i] == 0:
			ind = has[b[i]]
			time += 2 * (ind - taken) + 1
			for j in range(maxi, ind):
				if a[j] in has2:
					bol[has2[a[j]]] = 1
			maxi = ind
			taken += 1
		else:
			taken += 1
			time += 1
	print(time)


T = int(input())
for test in range(T):
	(N, M) = list(map(int, input().split()))
	alist = list(map(int, input().split()))
	blist = list(map(int, input().split()))
	indexlist = {a: n for (n, a) in enumerate(alist)}
	depth = 0
	moves = 0
	for (k, b) in enumerate(blist):
		index = indexlist[b]
		if index > depth:
			moves += 2 * index - 2 * k + 1
			depth = index
		else:
			moves += 1
	print(moves)


import sys

def fastio():
	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()

def debug(*var, sep=' ', end='\n'):
	print(*var, file=sys.stderr, end=end, sep=sep)
INF = 10 ** 20
MOD = 10 ** 9 + 7
I = lambda : list(map(int, input().split()))
from math import gcd
from math import ceil
from collections import defaultdict as dd, Counter
from bisect import bisect_left as bl, bisect_right as br
(t,) = I()
while t:
	t -= 1
	(n, m) = I()
	a = I()
	b = I()
	v = [0] * (n + 1)
	idx = 0
	ans = 0
	for i in range(m):
		if v[b[i]]:
			ans += 1
			continue
		while idx < n and a[idx] != b[i]:
			v[a[idx]] = 1
			idx += 1
		ans += 1 + 2 * (idx - i)
	print(ans)


from sys import stdin

def input():
	return stdin.readline()[:-1]

def intput():
	return int(input())

def sinput():
	return input().split()

def intsput():
	return map(int, sinput())
debugging = 1

def dprint(*args):
	if debugging:
		print(*args)
	else:
		pass
t = intput()
for _ in range(t):
	(n, m) = intsput()
	a = list(intsput())
	b = list(intsput())
	indexes = [-1] * 1000000
	passed = [0] * 1000000
	for i in range(n):
		indexes[a[i]] = i
	moves = 0
	k = 0
	jj = -1
	for x in b:
		if passed[x]:
			moves += 1
		else:
			for j in range(jj + 1, n):
				passed[a[j]] = 1
				jj = j
				if a[j] == x:
					break
			moves += (j - k) * 2 + 1
		k += 1
	print(moves)


for q in range(int(input())):
	(n, m) = [int(i) for i in input().split()]
	a = [int(i) for i in input().split()]
	b = [int(i) for i in input().split()]
	ind = {}
	for i in range(n):
		ind[a[i]] = i
	mxt = -1
	ans = 0
	for i in range(m):
		bb = b[i]
		index = ind[bb]
		if index < mxt:
			ans += 1
		else:
			mxt = index
			ans += 2 * (index - i) + 1
	print(ans)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	di = {}
	for i in range(n):
		di[a[i]] = i + 1
	affected = 0
	time = 0
	used = 0
	for each in b:
		used += 1
		if di[each] <= affected:
			time += 1
		else:
			affected = di[each]
			time += 2 * (affected - used) + 1
	print(time)


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()]
for _ in [0] * RI():
	(n, m) = RMI()
	a = RMI()
	b = RMI()
	done = set()
	h = 0
	t = 0
	for j in range(len(b)):
		if b[j] in done:
			t += 1
			continue
		while b[j] not in done:
			done.add(a[h])
			h += 1
		t += 2 * (h - j - 1) + 1
	print(t)


for _ in range(int(input())):
	(n, m) = [int(j) for j in input().split()]
	(a, b) = ([x - 1 for x in [int(j) for j in input().split()]], [x - 1 for x in [int(j) for j in input().split()]])
	cp = a[:]
	for i in range(n):
		cp[a[i]] = i
	(count, result) = (-1, m)
	for i in range(m):
		if cp[b[i]] > count:
			result += 2 * (cp[b[i]] - i)
			count = cp[b[i]]
	print(result)


tebt = int(input())
for _ in range(tebt):
	(N, k) = map(int, input().split())
	l1 = list(map(int, input().split()))
	b = list(map(int, input().split()))
	arr = [0] * (N + 1)
	for i in range(1, N + 1):
		arr[l1[i - 1]] = i
	m = 1
	anb = 0
	for i in range(k):
		if arr[b[i]] <= m:
			anb = anb + 1
		else:
			anb += 2 * (arr[b[i]] - (i + 1)) + 1
		x = arr[b[i]]
		if x >= m:
			m = x
	print(anb)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	arr = list(map(int, input().split()))
	ls = list(map(int, input().split()))
	d = {}
	for i in range(n):
		d[arr[i]] = i
	f = 0
	lst = -1
	ans = 0
	for i in ls:
		if d[i] > lst:
			ans += 2 * (d[i] - f) + 1
			lst = d[i]
			f += 1
		else:
			ans += 1
			f += 1
	print(ans)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	l = [*map(int, input().split())]
	l1 = [*map(int, input().split())]
	dic = {}
	for i in range(n):
		dic[l[i]] = i
	x = -1
	y = 0
	z = 0
	for i in range(m):
		xx = l1[i]
		xy = dic[xx]
		if xy > x:
			z += xy - x
			x = xy
			y += 2 * z - 1
			z -= 1
		else:
			z -= 1
			y += 1
	print(y)


def main():
	t = int(input())
	for _ in range(t):
		(_n, _m) = [int(x) for x in input().split(' ')]
		a = [int(x) for x in input().split(' ')]
		b = [int(x) for x in input().split(' ')]
		answer = solve(a, b)
		print(answer)

def solve(a, b):
	whereis = {ai: i for (i, ai) in enumerate(a)}
	b_peak_idxs = [0]
	for (i, bi) in enumerate(b[1:]):
		if whereis[bi] > whereis[b[b_peak_idxs[-1]]]:
			b_peak_idxs.append(i + 1)
	(answer, j) = (0, 0)
	for (i, bi) in enumerate(b):
		if j < len(b_peak_idxs) and i == b_peak_idxs[j]:
			j += 1
			answer += (whereis[bi] - i) * 2 + 1
		else:
			answer += 1
	return answer
main()


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

def floor(n):
	if int(n) - n == 0:
		n = int(n)
	else:
		n = int(n) - 1
	return n

def main():
	t = int(input())
	for num in range(t):
		(n, m) = map(int, input().split())
		stack = GetList()
		gifts = GetList()
		dict = {}
		time = 0
		temp = -1
		for (i, gift) in enumerate(stack):
			dict[gift] = i
		k = 0
		while k < m:
			if dict[gifts[k]] > temp:
				temp = dict[gifts[k]]
				time += 2 * (temp - k) + 1
			else:
				time += 1
			k += 1
		print(time)
main()


t = int(input())
for kek in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	pos = dict()
	for i in range(len(a)):
		pos[a[i]] = i
	ans = 0
	m = 0
	for i in b:
		if pos[i] != 0:
			ans += 2 * (pos[i] - m) + 1
		else:
			ans += 2 * pos[i] + 1
		for j in range(pos[i], -1, -1):
			if pos[a[j]] == 0:
				break
			else:
				pos[a[j]] = 0
		m += 1
	print(ans)


import os
import sys
import math
from io import BytesIO, IOBase
input = sys.stdin.readline

def inp():
	return int(input())

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

def insr():
	s = input()
	return list(s[:len(s) - 1])

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

def dijkstra(start, distance, path, n):
	visited = [False for _ in range(n)]
	distance[start] = 0
	for i in range(n):
		v = -1
		for j in range(n):
			if not visited[v] and (v == -1 or distance[j] < distance[v]):
				v = j
		if distance[v] == math.inf:
			break
		visited[v] = True
		for edge in adj[v]:
			destination = edge[0]
			weight = edge[1]
			if distance[v] + weight < distance[destination]:
				distance[destination] = distance[v] + weight
				path[destination] = v

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

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

def ncr(n, r):
	return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))

def npr(n, r):
	return math.factorial(n) // math.factorial(n - r)

def seive(n):
	primes = [True] * (n + 1)
	ans = []
	for i in range(2, n):
		if not primes[i]:
			continue
		j = 2 * i
		while j <= n:
			primes[j] = False
			j += i
	for p in range(2, n + 1):
		if primes[p]:
			ans += [p]
	return ans

def factors(n):
	factors = []
	x = 1
	while x * x <= n:
		if n % x == 0:
			if n // x == x:
				factors.append(x)
			else:
				factors.append(x)
				factors.append(n // x)
		x += 1
	return factors

def main():
	try:
		for _ in range(inp()):
			(n, m) = invr()
			a = inlt()
			b = inlt()
			aidx = {}
			ans = 0
			prev = None
			for i in range(n):
				aidx[a[i]] = i
			for i in range(m):
				if prev is not None and aidx[b[i]] < aidx[prev]:
					ans += 1
				else:
					ans += 2 * (aidx[b[i]] - i) + 1
					prev = b[i]
			print(ans)
	except Exception as e:
		print(e)
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))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	aa = list(map(int, input().split()))
	bb = list(map(int, input().split()))
	ans = 0
	ind = 0
	vis = [0 for i in range(n)]
	co = 0
	for i in range(m):
		if vis[bb[i] - 1] == 1:
			ans += 1
			co -= 1
			continue
		while ind < n:
			co += 1
			if aa[ind] == bb[i]:
				vis[aa[ind] - 1] = 1
				ind += 1
				break
			else:
				vis[aa[ind] - 1] = 1
				ind += 1
		co -= 1
		ans += co * 2 + 1
	print(ans)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	ans = 0
	a = a[::-1]
	d = [0] * n
	ni = 0
	for i in b:
		if d[i - 1] == 1:
			ans += 1
			ni -= 1
		else:
			while True:
				x = a.pop()
				if x == i:
					ans += 2 * ni + 1
					break
				d[x - 1] = 1
				ni += 1
	print(ans)


import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
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))
input = lambda : sys.stdin.readline().rstrip('\r\n')
for t in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	pos = [0] * n
	for i in range(n):
		pos[a[i] - 1] = i
	top = -1
	cost = m
	for i in range(m):
		p = pos[b[i] - 1]
		if p > top:
			cost += 2 * (p - i)
			top = p
	print(cost)


import sys
input = sys.stdin.readline

def getInt():
	return int(input())

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

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

def getStr():
	return input().strip()
t = getInt()
for _ in range(t):
	(n, m) = getVars()
	a = getList()
	b = getList()
	d = {}
	res1 = []
	res2 = 0
	res = 0
	stopka = 0
	maxi = 0
	for i in range(m):
		if b[i] in d:
			res += 1
			stopka -= 1
			continue
		for j in range(maxi, n):
			if a[j] == b[i]:
				res += 2 * stopka + 1
				maxi = j + 1
				break
			else:
				d[a[j]] = 1
				stopka += 1
	print(res)


t = int(input())
while t:
	t = t - 1
	(n, m) = [int(s) for s in input().split()]
	a = [int(s) for s in input().split()]
	b = [int(s) for s in input().split()]
	d = {}
	for i in range(n):
		d[a[i]] = i + 1
	position_a = []
	for i in b:
		position_a.append(d[i])
	total_time = 0
	pos_grater = 0
	item_gone = 0
	for i in position_a:
		if i > pos_grater:
			total_time = total_time + 2 * (i - item_gone - 1) + 1
			pos_grater = i
			item_gone = item_gone + 1
		else:
			total_time = total_time + 1
			item_gone = item_gone + 1
	print(total_time)


tt = int(input())
for i in range(tt):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	new = set()
	h = 0
	t = 0
	for j in range(len(b)):
		if b[j] in new:
			t += 1
			continue
		while b[j] not in new:
			new.add(a[h])
			h += 1
		t += 2 * (h - j - 1) + 1
	print(t)


for q11 in range(int(input())):
	(n, m) = map(int, input().split())
	a = [int(q) - 1 for q in input().split()]
	s = [int(q) - 1 for q in input().split()]
	d = [0] * n
	for q in range(n):
		d[a[q]] = q
	(max1, ans) = (-1, 0)
	for q in range(m):
		if d[s[q]] > max1:
			ans += 2 * (d[s[q]] - q) + 1
			max1 = d[s[q]]
		else:
			ans += 1
	print(ans)


T = int(input())
for _ in range(T):
	(N, M) = map(int, input().split())
	A = [int(a) - 1 for a in input().split()]
	B = [int(a) - 1 for a in input().split()]
	X = [0] * N
	for (i, a) in enumerate(A):
		X[a] = i
	ans = 0
	ma = -1
	for (i, b) in enumerate(B):
		ans += (X[b] - i) * 2 + 1 if X[b] > ma else 1
		ma = max(ma, X[b])
	print(ans)


t = int(input())
while t:
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	da = {}
	maxi = -1
	for i in range(0, len(a)):
		da[a[i]] = i
	ans = 0
	for i in range(0, len(b)):
		if maxi < da[b[i]]:
			ans += 2 * (da[b[i]] - i) + 1
			maxi = da[b[i]]
		else:
			ans += 1
	print(ans)
	t = t - 1


import sys
import bisect as b
input = sys.stdin.readline

def cin():
	return map(int, sin().split())

def ain():
	return list(map(int, sin().split()))

def sin():
	return input()

def inin():
	return int(input())
for i in range(inin()):
	(n, m) = cin()
	l = ain()
	l1 = ain()
	d1 = dict()
	for i in range(n):
		d1[l[i]] = d1.get(l[i], 0) + i
	ma = d1[l1[0]]
	frn = 1
	s = 0
	for i in range(m):
		if i == 0:
			s += 2 * d1[l1[i]] + 1
		elif d1[l1[i]] <= ma:
			s += 1
			frn += 1
		else:
			ma = d1[l1[i]]
			s += 2 * (d1[l1[i]] - frn) + 1
			frn += 1
	print(s)


import sys
import math
t = int(input())
while t:
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	ind = {}
	for i in range(n):
		ind[a[i]] = i
	mi = 0
	ans = 0
	gne = 0
	for i in range(m):
		if ind[b[i]] <= mi:
			ans += 1
			gne += 1
		else:
			mi = ind[b[i]]
			ans += 2 * (mi - gne) + 1
			gne += 1
	print(ans)
	t -= 1


import sys
input = sys.stdin.readline
Q = int(input())
Query = []
for _ in range(Q):
	(N, M) = map(int, input().split())
	A = list(map(int, input().split()))
	B = list(map(int, input().split()))
	Query.append((N, M, A, B))
for (N, M, A, B) in Query:
	Ind = [None] * (N + 1)
	for (i, a) in enumerate(A):
		Ind[a] = i
	max_ind = -1
	ans = 0
	for (i, b) in enumerate(B):
		if Ind[b] > max_ind:
			ans += 2 * (Ind[b] - i) + 1
			max_ind = Ind[b]
		else:
			ans += 1
	print(ans)


def ternary(n):
	if n == 0:
		return '0'
	nums = []
	while n:
		(n, r) = divmod(n, 3)
		nums.append(str(r))
	return ''.join(reversed(nums))
t = int(input())
for _ in range(t):
	(n, m) = [int(x) for x in input().split()]
	dict = {}
	s = list(map(int, input().split()))
	for i in range(n):
		dict[s[i]] = i + 1
	s = list(map(int, input().split()))
	for i in range(m):
		s[i] = dict[s[i]]
	dict = {}
	count = 0
	max_index = 0
	removed = 0
	for i in range(m):
		if s[i] < max_index:
			count += 1
			removed += 1
		else:
			count += 2 * (s[i] - 1 - removed)
			count += 1
			removed += 1
		max_index = max(max_index, s[i])
	print(count)


import os
import sys
from io import BytesIO, IOBase
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))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def list2d(a, b, c):
	return [[c] * b for i in range(a)]

def list3d(a, b, c, d):
	return [[[d] * c for j in range(b)] for i in range(a)]

def list4d(a, b, c, d, e):
	return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]

def ceil(x, y=1):
	return int(-(-x // y))

def Yes():
	print('Yes')

def No():
	print('No')

def YES():
	print('YES')

def NO():
	print('NO')
INF = 10 ** 18
MOD = 10 ** 9 + 7
Ri = lambda : [int(x) for x in sys.stdin.readline().split()]
ri = lambda : sys.stdin.readline().strip()
for _ in range(int(ri())):
	(n, m) = Ri()
	a = Ri()
	b = Ri()
	dic = {}
	for i in range(len(a)):
		dic[a[i]] = i
	cur = 0
	offset = 0
	ans = 0
	while True:
		if cur >= len(b):
			break
		top = b[cur]
		postop = dic[top] - offset
		tcur = cur + 1
		while tcur < len(b) and dic[b[tcur]] - offset < postop:
			tcur += 1
		tcur -= 1
		ans += postop * 2 + 1
		ans += tcur - cur
		offset += tcur - cur + 1
		cur = tcur + 1
	print(ans)


t = int(input())
for tc in range(t):
	(n, m) = [int(x) for x in input().split()]
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	loc = dict()
	for i in range(n):
		loc[a[i]] = i
	t = 0
	p = 0
	j = 0
	while j < m:
		d = loc[b[j]] - p
		t += 2 * d + 1
		j += 1
		tp = 1
		while j < m and loc[b[j]] - p < d:
			tp += 1
			t += 1
			j += 1
		p += tp
	print(t)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	pos = [0] * (n + 1)
	for i in range(0, len(a)):
		pos[a[i]] = i
	ptr = 0
	ans = 0
	for i in range(0, len(b)):
		if pos[b[i]] > ptr:
			ans += 2 * (pos[b[i]] - i) + 1
			ptr = pos[b[i]]
		else:
			ans += 1
	print(ans)


from sys import stdin
input = stdin.readline
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	g = a[:] + [0]
	for i in range(n):
		g[a[i]] = i
	s = 0
	mm = 0
	for i in range(m):
		if g[b[i]] > mm:
			s += 2 * (g[b[i]] - i) + 1
			mm = max(mm, g[b[i]])
		else:
			s += 1
	print(s)


t = int(input())
while t != 0:
	t -= 1
	(n, m) = map(int, input().split())
	a = [int(x) - 1 for x in input().split()]
	b = [int(x) - 1 for x in input().split()]
	pos = [0] * n
	ans = m
	for i in range(n):
		pos[a[i]] = i
	lst = -1
	for i in range(m):
		if pos[b[i]] > lst:
			ans += 2 * (pos[b[i]] - i)
			lst = pos[b[i]]
	print(ans)


import os, sys
from io import BytesIO, IOBase
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))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from math import ceil
mod = 10 ** 9 + 7
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	presents = list(map(int, input().split()))
	order = list(map(int, input().split()))
	memo = {}
	for i in range(n):
		memo[presents[i]] = i
	minimum_time = 0
	count_seen = 0
	current_index = [0 for _ in range(m)]
	max_index = float('-inf')
	for i in range(m):
		current_index[i] = memo[order[i]]
	for i in range(m):
		if i == 0:
			minimum_time += current_index[i] * 2 + 1
			max_index = current_index[i]
		elif current_index[i] > max_index:
			max_index = current_index[i]
			minimum_time += (current_index[i] - count_seen) * 2 + 1
		else:
			minimum_time += 1
		count_seen += 1
	print(minimum_time)


import sys, math
input = sys.stdin.readline

def inp():
	return int(input())

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

def insr():
	s = input()
	return s[:len(s) - 1]

def invr():
	return map(int, input().split())
t = 1
t = inp()
for tt in range(t):
	(n, m) = invr()
	a = inlt()
	b = inlt()
	q = [-1] * len(a)
	c = 0
	for i in range(len(a)):
		q[a[i] - 1] = i
	w = 0
	qw = 0
	for i in range(len(b)):
		if q[b[i] - 1] < w:
			c = c + 1
			qw = qw + 1
		else:
			w = q[b[i] - 1]
			c = c + 2 * (w - qw) + 1
			qw = qw + 1
	print(c)


import sys
input = sys.stdin.buffer.readline
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	dic = {}
	for (i, el) in enumerate(map(int, input().split())):
		dic[el] = i
	(ma, t) = (0, 0)
	a = 0
	for el in map(int, input().split()):
		if dic[el] > ma:
			ma = dic[el]
			t += 2 * (ma - a) + 1
			a += 1
		else:
			t += 1
			a += 1
	print(t)


from sys import stdin
from bisect import bisect_right
t = int(stdin.readline().strip())
for _ in range(t):
	(n, m) = list(map(int, stdin.readline().split()))
	arr = list(map(int, stdin.readline().split()))
	barr = list(map(int, stdin.readline().split()))
	arr.reverse()
	barr.reverse()
	myset = set()
	ans = 0
	for i in range(m):
		want = barr.pop()
		if want in myset:
			ans += 1
			myset.remove(want)
		else:
			count = len(myset)
			while arr[-1] != want:
				count += 1
				myset.add(arr.pop())
			arr.pop()
			ans += 2 * count + 1
	print(ans)


t = int(input())
for you in range(t):
	l = input().split()
	n = int(l[0])
	m = int(l[1])
	a = input().split()
	ai = [int(i) for i in a]
	hashi = dict()
	for i in range(n):
		hashi[ai[i]] = i
	b = input().split()
	bi = [int(i) for i in b]
	curr = -1
	ans = 0
	numofel = 0
	for i in range(m):
		if curr == -1:
			ans = ans + 2 * hashi[bi[i]] + 1
			curr = hashi[bi[i]]
			numofel += 1
		if hashi[bi[i]] < curr:
			ans += 1
			numofel += 1
		elif hashi[bi[i]] > curr:
			ans = ans + 2 * (hashi[bi[i]] - numofel) + 1
			numofel += 1
			curr = hashi[bi[i]]
	print(ans)


t = int(input(''))
for v in range(t):
	a = input('').split(' ')
	n = int(a[0])
	m = int(a[1])
	a = list(map(int, input('').split(' ')))
	b = list(map(int, input('').split(' ')))
	d = {}
	for i in range(n):
		d[a[i]] = i + 1
	mx = 0
	ans = 0
	for i in range(m):
		if d[b[i]] < mx:
			ans = ans + 1
			continue
		else:
			k = d[b[i]] - 1 - i
			ans = ans + 2 * k + 1
			mx = d[b[i]]
	print(ans)


import math
testCases = int(input())
for _ in range(testCases):
	(n, m) = map(int, input().split())
	pendingGifts = tuple(map(int, input().split()))
	sendableGifts = tuple(map(int, input().split()))
	positions = [0] * n
	for index in range(n):
		positions[pendingGifts[index] - 1] = index
	a = -1
	total = m
	for index in range(m):
		itsPosition = positions[sendableGifts[index] - 1]
		if itsPosition > a:
			total += (itsPosition - index) * 2
			a = itsPosition
	print(total)


import sys
input = sys.stdin.readline
t = int(input())
for test in range(t):
	(n, m) = map(int, input().split())
	A = list(map(int, input().split()))
	B = list(map(int, input().split()))
	A_INV = [-1] * (n + 1)
	for (ind, a) in enumerate(A):
		A_INV[a] = ind
	USEMAXIND = -1
	USEITEM = 0
	ANS = 0
	for b in B:
		if A_INV[b] > USEMAXIND:
			ANS += 2 * (A_INV[b] - USEITEM) + 1
			USEITEM += 1
			USEMAXIND = A_INV[b]
		else:
			USEITEM += 1
			ANS += 1
	print(ANS)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	rec = {}
	for i in range(n):
		rec[a[i]] = i
	ans = 0
	lim = 0
	for i in range(m):
		if rec[b[i]] > lim:
			ans += 2 * (rec[b[i]] - i) + 1
			lim = rec[b[i]]
		else:
			ans += 1
	print(ans)


t = int(input())
for w in range(t):
	(n, m) = list(map(int, input().split()))
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	seen = set()
	stack = []
	for i in reversed(range(n)):
		stack.append(a[i])
	cost = 0
	for val in b:
		cost += 1
		if val in seen:
			seen.remove(val)
		else:
			cost += 2 * len(seen)
			nextVal = -1
			while True:
				nextVal = stack.pop()
				if val is nextVal:
					break
				seen.add(nextVal)
				cost += 2
	print(cost)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	stack = list(map(int, input().split()))
	order = list(map(int, input().split()))
	dic = {}
	for i in range(1, len(stack) + 1):
		dic[stack[i - 1]] = i
	mx = dic[order[0]]
	r = 2 * (mx - 1) + 1
	subtract = 1
	for i in order[1:]:
		if dic[i] < mx:
			r += 1
			subtract += 1
		else:
			r += (dic[i] - subtract - 1) * 2 + 1
			mx = dic[i]
			subtract += 1
	print(r)


def check(stackSize, wishSize, stack, wish):
	stackLoc = {}
	wishLoc = {}
	l = max(stackSize, wishSize)
	for i in range(l):
		if i < stackSize:
			stackLoc[stack[i]] = i + 1
	ans = 0
	deepest = 1
	giftTakens = 0
	for (i, w) in enumerate(wish):
		loc = stackLoc[w]
		if loc <= deepest:
			ans += 1
		else:
			ans += 2 * (loc - giftTakens - 1) + 1
		deepest = max(loc, deepest)
		giftTakens += 1
	return ans
numTestCase = int(input())
for i in range(numTestCase):
	(stackSize, wishSize) = map(int, input().split())
	stack = list(map(int, input().split()))
	wish = list(map(int, input().split()))
	print(check(stackSize, wishSize, stack, wish))


t = int(input())
for hh in range(0, t):
	(n, m) = [int(x) for x in input().split()]
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	d = dict()
	ans = 0
	for i in range(0, len(a)):
		d[a[i]] = i + 1
	maxdepth = 1
	for i in range(0, len(b)):
		pos = d[b[i]]
		if pos <= maxdepth:
			ans += 1
		else:
			maxdepth = pos
			ans += 2 * (maxdepth - i - 1) + 1
	print(ans)


import sys
import math
import bisect
import heapq
from bisect import bisect_right
from sys import stdin, stdout

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

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

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

def get_list_of_list(n):
	return [list(map(int, sys.stdin.readline().strip().split())) for _ in range(n)]

def get_string():
	return sys.stdin.readline().strip()

def myceil(x, y):
	return (x + y - 1) // y

def Solution(a, b, n, m):
	ans = 0
	pos = [0 for _ in range(n + 1)]
	for i in range(n):
		pos[a[i]] = i
	indx = -1
	for i in range(m):
		if pos[b[i]] > indx:
			ans += 2 * (pos[b[i]] - i) + 1
			indx = pos[b[i]]
		else:
			ans += 1
	print(ans)

def main():
	for _ in range(get_int()):
		(n, m) = get_ints_in_variables()
		a = get_ints_in_list()
		b = get_ints_in_list()
		Solution(a, b, n, m)
main()


import sys
reader = (list(map(int, line.split())) for line in sys.stdin)
input = reader.__next__
(t,) = input()
for _ in range(t):
	(n, m) = input()
	a = list(input())
	b = list(input())
	d = {el: i for (i, el) in enumerate(a)}
	maxPos = d[b[0]]
	ans = 2 * maxPos + 1
	Nremoved = 1
	for el in b[1:]:
		pos = d[el]
		if pos < maxPos:
			ans += 1
		else:
			ans += 2 * (pos - Nremoved) + 1
			maxPos = pos
		Nremoved += 1
	print(ans)


from sys import *
t = int(stdin.readline())
for _ in range(t):
	(n, k) = map(int, stdin.readline().split())
	a = list(map(int, stdin.readline().split()))
	b = list(map(int, stdin.readline().split()))
	pos = [0] * (max(a) + 1)
	for i in range(n):
		pos[a[i]] = i
	m = j = pos[b[0]]
	ans = m * 2 + 1
	l = 1
	for i in range(1, k):
		if pos[b[i]] > j:
			j = pos[b[i]]
			m = pos[b[i]] - l
			ans += m * 2 + 1
		else:
			ans += 1
		l += 1
	print(ans)


from operator import itemgetter
t = int(input())

def solve(n, m, a, b):
	cnt = 0
	carry = 0
	b_set = set(b)
	b.reverse()
	a.reverse()
	b_seen = set([])
	while b:
		if not b[-1] in b_seen:
			b_top = b.pop()
			while True:
				a_tmp = a.pop()
				if not a_tmp == b_top:
					if a_tmp in b_set:
						b_seen.add(a_tmp)
					carry += 1
				else:
					cnt += 2 * carry + 1
					break
		else:
			b.pop()
			cnt += 1
			carry -= 1
	print(cnt)
for i in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	solve(n, m, a, b)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	d = dict()
	for (i, v) in enumerate(a, 1):
		d[v] = i
	pointer = 0
	ans = 0
	t = 0
	for x in b:
		ind = d[x]
		if ind <= pointer:
			ans += 1
		else:
			ans += (ind - 1 - t) * 2 + 1
			pointer = ind
		t += 1
	print(ans)


from collections import Counter
from collections import defaultdict
import math
import random

def inp():
	return map(int, input().split())
mod = int(1000000000.0) + 7

def solve(a, n):
	pass
for _ in range(int(input())):
	(n, m) = inp()
	a = list(inp())
	b = list(inp())
	ans = 0
	ia = 0
	ib = 0
	ans = dict()
	for i in range(m):
		ans[b[i]] = 0
	left = 0
	while ib < m:
		if ans[b[ib]] == 0:
			k = 0
			while ia < n and b[ib] != a[ia]:
				try:
					if ans[a[ia]] == 0:
						ans[a[ia]] = 1
				except Exception:
					pass
				ia += 1
				k += 1
			left += k
			ia += 1
			ans[b[ib]] = 2 * left + 1
		else:
			left -= 1
		ib += 1
	print(sum(ans.values()))


import os, sys, math
import collections
if os.path.exists('testing'):
	name = os.path.basename(__file__)
	if name.endswith('.py'):
		name = name[:-3]
	src = open(name + '.txt', encoding='utf8')
	input = src.readline

def solve():
	positions = {gift: index for (index, gift) in enumerate(ass)}
	total_time = 0
	max_reordered_index = 0
	for (e, gift) in enumerate(bs):
		index = positions[gift] - e
		if index < max_reordered_index:
			k = 0
			max_reordered_index -= 1
		else:
			k = index
			max_reordered_index = index
		total_time += 2 * k + 1
	return total_time

def string():
	return input().strip()

def array_of_strings(q):
	return [input().strip() for _ in range(q)]

def integers():
	return map(int, input().strip().split())

def array_of_integers(q):
	return [tuple(map(int, input().strip().split())) for _ in range(q)]
(t,) = integers()
for _ in range(t):
	(n, m) = integers()
	ass = list(integers())
	bs = list(integers())
	res = solve()
	print(res)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))[::-1]
	b = list(map(int, input().split()))
	min_idx = n
	d = {}
	for i in range(n):
		d[a[i]] = i
	ans = 0
	on_top = 0
	for i in b:
		if d[i] > min_idx:
			on_top -= 1
			ans += 1
		else:
			on_top += min_idx - d[i] - 1
			ans += 2 * on_top + 1
			min_idx = d[i]
	print(ans)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	A = list(map(int, input().split()))
	B = list(map(int, input().split()))
	DA = {}
	for (i, a) in enumerate(A):
		DA[a] = i
	cur = -1
	cnt = 0
	ans = 0
	for b in B:
		j = DA[b]
		if j > cur:
			ans += 2 * (j - cnt) + 1
			cur = j
			cnt += 1
		else:
			ans += 1
			cnt += 1
	print(ans)


t = int(input())
for i in range(t):
	inp = list(map(int, input().split()))
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	l = {}
	for j in range(len(a)):
		l[a[j]] = j
	maxi = 0
	count = 0
	tot = 0
	for j in range(len(b)):
		if l[b[j]] > maxi:
			x = l[b[j]] - count
			tot += 2 * x + 1
			maxi = l[b[j]]
			count += 1
		else:
			tot += 1
			count += 1
	print(tot)


from bisect import bisect_left as bl
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	x = -1
	r = 0
	al = {a[i]: i for i in range(n)}
	y = 0
	for i in b:
		c = al[i]
		if c > x:
			r += 1 + 2 * (c - y)
			x = c
		else:
			r += 1
		y += 1
	print(r)


from sys import stdin
input = stdin.readline
R = lambda : map(int, input().split())
for _ in range(int(input())):
	(n, m) = R()
	v = [0] * n
	j = 0
	k = s = t = 0
	for i in R():
		v[i - 1] = j
		j += 1
	for i in R():
		if v[i - 1] == k:
			s += t * 2 + 1
			k += 1
		elif v[i - 1] < k:
			t -= 1
			s += 1
		else:
			s += (t + v[i - 1] - k) * 2 + 1
			t += v[i - 1] - k
			k = v[i - 1] + 1
	print(s)


import os
import sys
from math import *
from collections import *
from bisect import *
from io import BytesIO, IOBase
from fractions import *

def vsInput():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
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))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def value():
	return tuple(map(int, input().split()))

def array():
	return [int(i) for i in input().split()]

def Int():
	return int(input())

def Str():
	return input()

def arrayS():
	return [i for i in input().split()]
for _ in range(Int()):
	(n, m) = value()
	st = array()[::-1]
	ind = {st[i]: i for i in range(n)}
	a = array()
	ans = 0
	last = inf
	for i in range(m):
		if ind[a[i]] < last:
			top = n - ind[a[i]] - 1 - i
			last = ind[a[i]]
			ans += 2 * top
		ans += 1
	print(ans)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = [x - 1 for x in list(map(int, input().split()))]
	b = [x - 1 for x in list(map(int, input().split()))]
	pos = a[:]
	for i in range(n):
		pos[a[i]] = i
	ans = m
	lst = -1
	for i in range(m):
		if pos[b[i]] > lst:
			ans += 2 * (pos[b[i]] - i)
			lst = pos[b[i]]
	print(ans)


def kkk(a, b):
	c = [0] * (len(a) + 1)
	for i in range(len(a)):
		c[a[i]] = i + 1
	ans = 0
	max_item = 0
	for i in range(len(b)):
		x = b[i]
		x = c[x]
		if x <= max_item:
			ans += 1
		else:
			max_item = x
			ans += 2 * (x - i - 1) + 1
	return ans
for i in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	print(kkk(a, b))


T = int(input())
for _ in range(T):
	(n, m) = map(int, input().split())
	A = [int(x) - 1 for x in input().split()]
	B = [int(x) - 1 for x in input().split()]
	to_idx = {x: i for (i, x) in enumerate(B)}
	A = [to_idx[x] if x in to_idx else None for x in A]
	B = [to_idx[x] for x in B]
	to_depth = {x: i for (i, x) in enumerate(A)}
	depth = 0
	tot = 0
	for (i, b) in enumerate(B):
		curr = to_depth[i]
		if curr > depth:
			tot += 2 * (curr - i) + 1
			depth = curr
		else:
			tot += 1
	print(tot)


t = int(input())
while t:
	t -= 1
	(n, m) = map(int, input().split())
	(*a,) = map(int, input().split())
	(*b,) = map(int, input().split())
	d = {}
	for i in range(n):
		d[a[i]] = i
	ans = 0
	r = 0
	mx = -1
	for i in range(m):
		if mx < d[b[i]]:
			ans += (d[b[i]] - r) * 2 + 1
			mx = d[b[i]]
		else:
			ans += 1
		r += 1
	print(ans)


import sys
input = sys.stdin.readline
from collections import defaultdict
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	idx = defaultdict(int)
	for i in range(n):
		idx[a[i]] = i
	b = list(map(int, input().split()))
	removed = 0
	max_idx = -1
	ans = 0
	for bi in b:
		if max_idx > idx[bi]:
			ans += 1
		else:
			k = idx[bi] - removed
			ans += 2 * k + 1
			max_idx = idx[bi]
		removed += 1
	print(ans)


q = int(input())
for rer in range(q):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	for i in range(n):
		a[i] -= 1
	for i in range(m):
		b[i] -= 1
	mapa = [0] * n
	for i in range(n):
		mapa[a[i]] = i
	for i in range(m):
		b[i] = mapa[b[i]]
	najn = -100000
	wyj = 0
	sek = 0
	for i in range(m):
		if b[i] > najn:
			sek += 2 * (b[i] - wyj) + 1
			wyj += 1
			najn = b[i]
		else:
			sek += 1
			wyj += 1
	print(sek)


nn = int(input())
for tc in range(nn):
	f = list(map(int, input().split(' ')))
	n = f[0]
	m = f[1]
	cad = list(map(int, input().split(' ')))
	picks = list(map(int, input().split(' ')))
	reverse_order = [-1 for _ in range(n + 1)]
	sec = 0
	max_vu = -1
	for (i, c) in enumerate(cad):
		reverse_order[c] = i
	for (i, p) in enumerate(picks):
		idx = reverse_order[p]
		if idx < max_vu:
			sec += 1
		else:
			max_vu = idx
			sec += 2 * (idx - i) + 1
	print(sec)


import os
import sys
from io import BytesIO, IOBase

def solve(n, m, a, b):
	posa = dict([(ai, i) for (i, ai) in enumerate(a)])
	(mpos, ans) = (-1, 0)
	for i in range(m):
		ans += 1 if mpos > posa[b[i]] else 2 * (posa[b[i]] - i) + 1
		mpos = max(posa[b[i]], mpos)
	return ans

def main():
	for _ in range(int(input().strip())):
		[n, m] = map(int, input().strip().split())
		a = list(map(int, input().strip().split()))
		b = list(map(int, input().strip().split()))
		print(solve(n, m, a, b))
from types import GeneratorType

def bootstrap(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		else:
			to = f(*args, **kwargs)
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						break
					to = stack[-1].send(to)
			return to
	return wrappedfunc
py2 = round(0.5)
if py2:
	from future_builtins import ascii, filter, hex, map, oct, zip
	range = xrange
import os, sys
from io import IOBase, BytesIO
BUFSIZE = 8192

class FastIO(BytesIO):
	newlines = 0

	def __init__(self, file):
		self._file = file
		self._fd = file.fileno()
		self.writable = 'x' in file.mode or 'w' in file.mode
		self.write = super(FastIO, self).write if self.writable else None

	def _fill(self):
		s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
		self.seek((self.tell(), self.seek(0, 2), super(FastIO, self).write(s))[0])
		return s

	def read(self):
		while self._fill():
			pass
		return super(FastIO, self).read()

	def readline(self):
		while self.newlines == 0:
			s = self._fill()
			self.newlines = s.count(b'\n') + (not s)
		self.newlines -= 1
		return super(FastIO, self).readline()

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

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		if py2:
			self.write = self.buffer.write
			self.read = self.buffer.read
			self.readline = self.buffer.readline
		else:
			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))
input = lambda : sys.stdin.readline()
import sys

class ostream:

	def __lshift__(self, a):
		sys.stdout.write(str(a))
		return self
cout = ostream()
endl = '\n'

def readnumbers(zero=0):
	conv = ord if py2 else lambda x: x
	A = []
	numb = zero
	sign = 1
	i = 0
	s = sys.stdin.buffer.read()
	try:
		while True:
			if s[i] >= b'0'[0]:
				numb = 10 * numb + conv(s[i]) - 48
			elif s[i] == b'-'[0]:
				sign = -1
			elif s[i] != b'\r'[0]:
				A.append(sign * numb)
				numb = zero
				sign = 1
			i += 1
	except:
		pass
	if s and s[-1] >= b'0'[0]:
		A.append(sign * numb)
	return A
main()


from collections import deque
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = [int(i) for i in input().split()]
	b = [int(i) for i in input().split()]
	a = deque(a)
	i = 0
	t = 0
	st = set()
	while i < m:
		gift = b[i]
		if gift not in st:
			t += len(st) * 2
			while a[0] != gift:
				st.add(a.popleft())
				t += 2
			a.popleft()
			t += 1
		else:
			st.remove(gift)
			t += 1
		i += 1
	print(t)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = [int(i) for i in input().split()]
	b = [int(i) for i in input().split()]
	d = {}
	for i in range(n):
		d[a[i]] = i
	ind = d[b[0]]
	ans = 2 * ind + 1
	c = 0
	for i in range(1, m):
		c += 1
		if d[b[i]] < ind:
			ans += 1
		else:
			ind = d[b[i]]
			ans += 2 * (ind - c) + 1
	print(ans)


n = int(input())
lst1 = []
lst2 = []
lst3 = []
for i in range(n):
	lst1.append([int(x) for x in input().split(' ')])
	lst2.append([int(x) for x in input().split(' ')])
	lst3.append([int(x) for x in input().split(' ')])
for i in range(n):
	stackLoc = {}
	for j in range(len(lst2[i])):
		stackLoc[lst2[i][j]] = j + 1
	sec = 0
	counter = 0
	checked = 1
	for ele in lst3[i]:
		loc = stackLoc[ele]
		if loc < checked:
			sec += 1
		else:
			sec += (loc - counter - 1) * 2 + 1
		checked = max(checked, loc)
		counter += 1
	print(sec)


t = int(input())
for i in range(t):
	cnt = 0
	cmp = 0
	res = 0
	temp = list(input().split())
	n = int(temp[0])
	m = int(temp[1])
	c = list(input().split())
	b = list(input().split())
	a = []
	for j in range(n):
		a.append(0)
	for j in range(n):
		c[j] = int(c[j])
	for j in range(n):
		a[c[j] - 1] = j
	for j in range(m):
		b[j] = int(b[j])
	for j in b:
		if cmp < a[j - 1]:
			res += 2 * (a[j - 1] - cnt) + 1
			cmp = a[j - 1]
		else:
			res += 1
		cnt += 1
	print(res)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	A = list(map(int, input().split()))
	B = list(map(int, input().split()))
	rA = [0] * (n + 1)
	for (i, a) in enumerate(A):
		rA[a] = i
	ans = m
	sent = 0
	max_i = -1
	for b in B:
		if rA[b] > max_i:
			ans += (rA[b] - sent) * 2
			max_i = rA[b]
		sent += 1
	print(ans)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	stack = list(map(int, input().split()))[::-1]
	task = list(map(int, input().split()))
	o1 = set()
	ans = 0
	for i in range(m):
		if task[i] in o1:
			ans += 1
			o1.remove(task[i])
			continue
		l = len(o1)
		while stack[-1] != task[i]:
			o1.add(stack.pop())
			l += 1
		stack.pop()
		ans += l * 2 + 1
	print(ans)


from collections import Counter, defaultdict, deque
from heapq import heappop, heappush, heapify
import sys, bisect, math, itertools, fractions, pprint
sys.setrecursionlimit(10 ** 8)
mod = 10 ** 9 + 7
mod2 = 998244353
INF = float('inf')

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

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

def inpln(n):
	return list((int(sys.stdin.readline()) for i in range(n)))
t = inp()
for i in range(t):
	(n, m) = inpl()
	a = inpl()
	b = inpl()
	d = dict()
	s = set()
	r = 0
	res = 0
	for (i, j) in enumerate(a):
		d[j] = i
	for (i, j) in enumerate(b):
		if j in s:
			res += 1
		else:
			res += (d[j] - i) * 2 + 1
			for l in a[r:d[j] + 1]:
				s.add(l)
			r = d[j] + 1
	print(res)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = list(map(lambda x: int(x) - 1, input().split()))
	b = list(map(lambda x: int(x) - 1, input().split()))
	seen = [False] * n
	index = 0
	removed = 0
	ans = 0
	for i in b:
		if seen[i]:
			ans += 1
			removed += 1
		else:
			while a[index] != i:
				seen[a[index]] = True
				index += 1
			ans += 2 * (index - removed) + 1
			removed += 1
			index += 1
	print(ans)


I = lambda : map(int, input().split())
for i in range(int(input())):
	(n, m) = I()
	(a, b) = (list(I()), list(I()))
	(l, q, w) = ([0] * (n + 1), 0, 0)
	for i in range(n):
		l[a[i]] = i
	for i in b:
		o = l[i]
		if o > q:
			m += (o - w) * 2
			q = o
		w += 1
	print(m)


t = int(input())
from math import *
import sys
input = sys.stdin.readline
while t > 0:
	t -= 1
	(n, m) = map(int, input().split())
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	flag = 0
	maxi = -9
	z = 0
	ind = [0 for i in range(n + 1)]
	v = [-9 for i in range(n + 1)]
	for i in range(m):
		v[b[i]] = i
	for i in range(n):
		if v[a[i]] != -9:
			ind[a[i]] = i
	c = 0
	j = 0
	p = 0
	prev = 0
	while j < m:
		if v[b[j]] == -12:
			c += 1
			v[b[j]] = -13
			j += 1
			p += 1
			continue
		else:
			c += 2 * (ind[b[j]] - p) + 1
		p += 1
		if j == m:
			break
		for i in range(prev, ind[b[j]]):
			if v[a[i]] != -9 and v[a[i]] != -13 and (v[a[i]] != -12):
				v[a[i]] = -12
		prev = ind[b[j]] + 1
		j += 1
	print(c)


import sys
ip = lambda : sys.stdin.readline().rstrip()
for _ in range(int(ip())):
	(n, m) = map(int, ip().split())
	a = list(map(int, ip().split()))
	b = list(map(int, ip().split()))
	d = set(b)
	ans = 0
	reached = 0
	shuffle = set()
	for i in range(len(b)):
		if b[i] in shuffle:
			ans += 1
			shuffle.remove(b[i])
			d.remove(b[i])
		elif b[i] in d:
			for j in range(reached, n):
				if a[j] == b[i]:
					idx = j
					reached = j + 1
					break
				elif a[j] in d:
					shuffle.add(a[j])
			idx -= i
			ans += 2 * idx + 1
	print(ans)


import sys
from itertools import accumulate
q = int(input())
for _ in range(q):
	(n, m) = map(int, input().split())
	pos = [0 for i in range(n)]
	a = list(map(int, input().split()))
	for i in range(n):
		pos[a[i] - 1] = i
	b = list(map(int, input().split()))
	b_pos = [0 for i in range(m)]
	for i in range(m):
		b_pos[i] = pos[b[i] - 1]
	max_depth = -1
	result = 0
	on_top_count = 0
	for i in range(m):
		x = b_pos[i]
		if x < max_depth:
			result += 1
		else:
			max_depth = x
			result += 2 * (x - on_top_count) + 1
		on_top_count += 1
	print(result)


from collections import *
for _ in range(int(input())):
	d = defaultdict(lambda : 0)
	ind = -1
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	for i in range(m):
		if d[b[i]] != 0:
			continue
		else:
			while 1:
				ind += 1
				if a[ind] != b[i]:
					d[a[ind]] = 1
				else:
					d[a[ind]] += 2 * (ind - i) + 1
					break
	sn = 0
	for i in b:
		sn += d[i]
	print(sn)


import heapq
from collections import defaultdict
t = int(input())
INF = 10 ** 10

def main():
	d = defaultdict(int)
	(n, m) = map(int, input().split())
	As = list(map(int, input().split()))
	Bs = list(map(int, input().split()))
	d_As_ind = {a: i for (i, a) in enumerate(As)}
	index_list = [d_As_ind[b] for b in Bs]
	x = 0
	cnt = 0
	for (i, ind) in enumerate(index_list):
		if ind > x:
			cnt += 2 * (ind - i) + 1
			x = ind
		else:
			cnt += 1
	print(cnt)
for _ in range(t):
	main()


from bisect import bisect_left as bl
from bisect import bisect_right as br
import heapq
import math
from collections import *
from functools import reduce, cmp_to_key
import sys
input = sys.stdin.readline

def factors(n):
	return sorted(list(set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))))

def li():
	return [int(i) for i in input().rstrip('\n').split(' ')]

def st():
	return input().rstrip('\n')

def val():
	return int(input().rstrip('\n'))

def li2():
	return [i for i in input().rstrip('\n').split(' ')]

def li3():
	return [int(i) for i in input().rstrip('\n')]
for _ in range(val()):
	(n, m) = li()
	a = li()
	b = li()
	s = set()
	ans = j = 0
	for i in b:
		if i not in s:
			while a[j] != i:
				s.add(a[j])
				j += 1
			ans += 2 * len(s)
			ans += 1
			j += 1
		else:
			s.remove(i)
			ans += 1
	print(ans)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	d = {}
	tot = 0
	ind = 0
	l = 0
	for i in range(m):
		if b[i] in d:
			tot += 1
			l -= 1
		else:
			for j in range(ind, n):
				if b[i] != a[j]:
					d[a[j]] = 1
					l += 1
				else:
					tot += 2 * l + 1
					ind = j + 1
					break
	print(tot)


for _ in ' ' * int(input()):
	(a, b) = map(int, input().split())
	pre = 0
	ans = 0
	z = [0] * (a + 1)
	for (i, j) in enumerate(map(int, input().split())):
		z[j] = i
	for (i, j) in enumerate(map(int, input().split())):
		if z[j] <= pre:
			ans += 1
		else:
			ans += 2 * (z[j] - i) + 1
			pre = z[j]
	print(ans)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	l1 = list(map(int, input().split()))
	l2 = list(map(int, input().split()))
	pos = [0] * n
	for i in range(n):
		pos[l1[i] - 1] = i
	a = -1
	sum = m
	for i in range(m):
		if pos[l2[i] - 1] > a:
			sum += (pos[l2[i] - 1] - i) * 2
			a = pos[l2[i] - 1]
	print(sum)


import sys

def get_ints():
	return map(int, sys.stdin.readline().strip().split())
for ad in range(int(input())):
	(n, m) = get_ints()
	a = list(get_ints())
	b = list(get_ints())
	pos = [-1] * (n + 1)
	x = -1
	ans = 0
	for i in range(n):
		pos[a[i]] = i
	for i in range(m):
		if pos[b[i]] < x:
			ans += 1
		else:
			ans += 2 * (pos[b[i]] - i) + 1
			x = pos[b[i]]
	print(ans)


N = int(input())
for _ in range(N):
	(n, m) = [int(x) for x in input().split()]
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	ans = 0
	i = 0
	j = 0
	found = set()
	fsize = 0
	while j < len(b):
		oi = i
		dfsize = 0
		while a[i] != b[j]:
			found.add(a[i])
			i += 1
			dfsize += 1
		ans += 2 * (i - oi + fsize) + 1
		fsize += dfsize
		i += 1
		j += 1
		while j < len(b) and b[j] in found:
			j += 1
			ans += 1
			fsize -= 1
	print(ans)


t = int(input())
for _ in range(t):
	(n, m) = list(map(int, input().split(' ')))
	a = list(map(int, input().split(' ')))
	b = list(map(int, input().split(' ')))
	order = [0] * (n + 1)
	for i in range(n):
		order[a[i]] = i
	pref_max = 0
	ans = 0
	for i in range(m):
		if order[b[i]] < pref_max:
			ans += 1
		else:
			pref_max = order[b[i]]
			ans += 2 * (order[b[i]] - i) + 1
	print(ans)


from sys import stdin, stdout
from math import gcd, ceil, sqrt
ii1 = lambda : int(stdin.readline().strip())
is1 = lambda : stdin.readline().strip()
iia = lambda : list(map(int, stdin.readline().strip().split()))
isa = lambda : stdin.readline().strip().split()
mod = 1000000007
tc = ii1()
for _ in range(tc):
	(n, m) = iia()
	pos = {}
	a = iia()
	for i in range(n):
		pos[a[i]] = i
	arranged = -1
	res = 0
	b = iia()
	for i in range(m):
		if pos[b[i]] > arranged:
			res += 2 * (pos[b[i]] - i) + 1
			arranged = pos[b[i]]
		else:
			res += 1
	print(res)


from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
import bisect
from heapq import *
from math import *
from collections import deque
from collections import Counter as counter
from itertools import combinations as comb
from itertools import permutations as permutate
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
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')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
mod = 1000000007

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

def out(var):
	sys.stdout.write(str(var))

def lis():
	return list(map(int, inp().split()))

def stringlis():
	return list(map(str, inp().split()))

def sep():
	return map(int, inp().split())

def strsep():
	return map(str, inp().split())

def graph(vertex):
	return [[] for i in range(0, vertex + 1)]

def zerolist(n):
	return [0] * n

def nextline():
	out('\n')

def testcase(t):
	for p in range(t):
		solve()

def printlist(a):
	for p in range(0, len(a)):
		out(str(a[p]) + ' ')

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

def power(a, b):
	ans = 1
	while b > 0:
		if b % 2 == 1:
			ans *= a
		a *= a
		b //= 2
	return ans

def ncr(n, r):
	return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))

def isPrime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	i = 5
	while i * i <= n:
		if n % i == 0 or n % (i + 2) == 0:
			return False
		i = i + 6
	return True

def bs(a, l, h, x):
	while l < h:
		mid = (l + h) // 2
		if a[mid] == x:
			return mid
		if a[mid] < x:
			l = mid + 1
		else:
			h = mid
	return l

def sieve(a):
	for i in range(3, 10 ** 6 + 1, 2):
		a[i] = 1
	for i in range(3, 10 ** 6 + 1, 2):
		for j in range(i * i, 10 ** 6 + 1, i):
			a[j] = 0
	a[2] = 1
	return a

def bfs(g, st):
	visited = [0] * len(g)
	visited[st] = 1
	queue = []
	queue.append(st)
	new = []
	while len(queue) != 0:
		s = queue.pop()
		new.append(s)
		for i in g[s]:
			if visited[i] == 0:
				visited[i] = 1
				queue.append(i)
	return new

def solve():
	(n, m) = sep()
	a = lis()
	b = lis()
	pos = [0] * (n + 1)
	for i in range(0, n):
		pos[a[i]] = i + 1
	maxpos = 0
	ans = 0
	for i in range(0, m):
		if pos[b[i]] > maxpos:
			ans += 2 * (pos[b[i]] - (i + 1)) + 1
		else:
			ans += 1
		maxpos = max(maxpos, pos[b[i]])
	print(ans)
testcase(int(inp()))


from collections import defaultdict
al = defaultdict(int)
a = int(input())
for i in range(a):
	al = defaultdict(int)
	(n, m) = map(int, input().split())
	z = list(map(int, input().split()))
	r = list(map(int, input().split()))
	for i in range(len(z)):
		al[z[i]] = i + 1
	j = 1
	cur = al[r[0]] - 1
	bok = 0
	total = 0
	tb = 0
	while j < len(r):
		if al[r[j]] <= cur:
			bok += 1
			j += 1
			flag = 0
		else:
			total += 2 * (cur - tb) + 1 + bok
			tb += bok + 1
			cur = al[r[j]] - 1
			bok = 0
			flag = 1
			j += 1
	total += 2 * (cur - tb) + 1 + bok
	print(total)


q = int(input())
for z in range(q):
	(n, m) = map(int, input().split())
	arr = list(map(int, input().split()))
	need = list(map(int, input().split()))
	t = 0
	stt = set(need)
	d = {}
	for i in range(n):
		d[arr[i]] = i
	st = set()
	used = [0 for i in range(n)]
	mxind = 0
	for z in range(m):
		cur = need[z]
		if cur in st:
			t += 1
			st.remove(cur)
			used[d[cur]] = 1
			continue
		for i in range(mxind, n):
			mxind = i + 1
			if arr[i] == cur:
				t += 1
				st.add(arr[i])
				break
			else:
				st.add(arr[i])
		st.remove(cur)
		t += 2 * len(st)
		used[d[cur]] = 1
	print(t)


for i in range(int(input())):
	(n, m) = [int(i) for i in input().split()]
	stk = [int(i) for i in input().split()][::-1]
	lst = [int(i) for i in input().split()]
	c1 = set()
	sz = 0
	ans = 0
	for i in lst:
		if i in c1:
			ans += 1
			sz -= 1
			c1.remove(i)
		else:
			k = 0
			while stk[-1] != i:
				k += 1
				c1.add(stk.pop())
			stk.pop()
			ans += 2 * (k + sz) + 1
			sz += k
	print(ans)


t = int(input())
for loop in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	for i in range(len(a)):
		a[i] -= 1
	for i in range(len(b)):
		b[i] -= 1
	dic = {}
	r = 0
	ans = 0
	for i in range(len(a)):
		dic[a[i]] = i
	for i in range(len(b)):
		if r > dic[b[i]]:
			ans += 1
		else:
			ans += (dic[b[i]] - i) * 2 + 1
			r = max(r, dic[b[i]])
	print(ans)


import sys
import heapq
from collections import defaultdict
t = int(sys.stdin.readline())
for _ in range(t):
	(n, m) = map(int, sys.stdin.readline().split())
	stack = list(map(int, sys.stdin.readline().split()))
	b = list(map(int, sys.stdin.readline().split()))
	dic = defaultdict(lambda : -1)
	in_heap = defaultdict(int)
	for i in range(m):
		dic[b[i]] = i
	count = 0
	heap = []
	limit = 0
	heapq.heapify(heap)
	for i in range(m):
		if in_heap[b[i]] == 1:
			count += 1
			heapq.heappop(heap)
		else:
			k = len(heap)
			j = limit
			while j < n:
				if stack[j] == b[i]:
					break
				else:
					limit += 1
					heapq.heappush(heap, [dic[stack[j]], stack[j]])
					in_heap[stack[j]] = 1
					k += 1
					j += 1
			limit = j + 1
			count += 2 * k + 1
	print(count)


from sys import stdin
from collections import deque
mod = 10 ** 9 + 7
import sys
from bisect import bisect_right
from bisect import bisect_left
from collections import defaultdict
from math import sqrt, factorial, gcd, log2, inf, ceil
import heapq
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	l1 = list(map(int, input().split()))
	l2 = list(map(int, input().split()))
	hash = defaultdict(int)
	seti = set(l2)
	for i in range(n):
		if l1[i] in seti:
			hash[l1[i]] = i
	st = []
	ans = 0
	s = set(l1)
	el = 0
	for i in range(m):
		if l2[i] in s:
			if st == []:
				z = hash[l2[i]]
				st.append(z)
				ans += 2 * z + 1
				el += 1
			else:
				z = hash[l2[i]]
				if st[0] > z:
					ans += 1
					el += 1
				else:
					ans += 2 * (z - el) + 1
					st.pop()
					st.append(z)
					el += 1
	print(ans)


t = int(input())
for _ in range(t):
	(n, m) = list(map(int, input().split()))
	pera = list(map(int, input().split()))
	perb = list(map(int, input().split()))
	pres = [0] * n
	for i in range(n):
		pres[pera[i] - 1] = i
	ans = 0
	maxi = -1
	for i in range(m):
		if pres[perb[i] - 1] > maxi:
			maxi = pres[perb[i] - 1]
			ans += 2 * (pres[perb[i] - 1] - i)
		ans += 1
	print(ans)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	nrr = list(map(int, input().split()))
	mrr = list(map(int, input().split()))
	mset = set(mrr)
	(ni, mi) = (0, 0)
	reordered = set()
	total = 0
	k = 1
	while mi < m:
		if nrr[ni] in reordered:
			total += 1
			k -= 1
		elif nrr[ni] == mrr[mi]:
			total += 2 * (k - 1) + 1
			k -= 1
			mi += 1
			if mi >= m:
				break
			while mrr[mi] in reordered:
				mi += 1
				total += 1
				k -= 1
				if mi >= m:
					break
		elif nrr[ni] in mset:
			reordered.add(nrr[ni])
		ni += 1
		k += 1
	print(total)


n = int(input())
for x in range(n):
	(a, b) = list(map(int, input().split()))
	array = list(map(int, input().split()))
	dic = {}
	index = 1
	for it in array:
		dic[it] = index
		index += 1
	count = 0
	current = 0
	answer = 0
	arr = list(map(int, input().split()))
	for it in arr:
		value = dic[it]
		if value > current:
			current = value
			answer += 2 * (value - 1 - count) + 1
			count += 1
		else:
			answer += 1
			count += 1
	print(answer)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	md = 0
	d = {a[i]: i for i in range(n)}
	s = 0
	sh = 0
	for i in range(m):
		if d[b[i]] - sh > md:
			s += 2 * (d[b[i]] - sh) + 1
			md = d[b[i]] - sh
		else:
			s += 1
		sh += 1
		md -= 1
	print(s)


case = int(input())
time = []
for i in range(case):
	k = input()
	k = k.split()
	n = int(k[0])
	m = int(k[1])
	stack = input()
	stack = list(map(int, stack.split()))
	send = input()
	send = list(map(int, send.split()))
	till_max = []
	max_mark = 0
	for j in range(m):
		for k in range(max_mark, n):
			if stack[k] == send[j]:
				if k >= max_mark:
					max_mark = k
					till_max.append([j, k])
				break
	total_time = 0
	till_mark = 0
	till_len = len(till_max)
	for j in range(m):
		if till_mark < till_len:
			if j == till_max[till_mark][0]:
				total_time = total_time + 2 * (till_max[till_mark][1] - j)
				till_mark += 1
		total_time += 1
	time.append(total_time)
for i in range(case):
	print(time[i])


import sys
import math

def read_line():
	return sys.stdin.readline()[:-1]

def read_int():
	return int(sys.stdin.readline())

def read_int_line():
	return [int(v) for v in sys.stdin.readline().split()]
t = read_int()
for i in range(t):
	(n, m) = read_int_line()
	a = read_int_line()
	b = read_int_line()
	v = [0] * n
	for i in range(n):
		v[a[i] - 1] = i
	k = 0
	time = 0
	ele = 0
	for i in range(m):
		if v[b[i] - 1] <= k:
			time += 1
		else:
			time += 2 * (v[b[i] - 1] - ele) + 1
			k = v[b[i] - 1]
		ele += 1
	print(time)


from collections import defaultdict
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	memo = [i for i in range(n)]
	d = defaultdict(int)
	for i in range(n):
		d[a[i]] = i
	ans = 0
	count = 0
	for bi in b:
		i = d[bi]
		if memo[i] == -1:
			ans += 1
			count += 1
		else:
			ans += (memo[i] - count) * 2 + 1
			count += 1
			memo[i] = -1
			for j in reversed(range(i)):
				if memo[j] == -1:
					break
				memo[j] = -1
	print(ans)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split(' '))
	a = list(map(int, input().split(' ')))
	b = list(map(int, input().split(' ')))
	pos = {}
	for i in range(n):
		pos[a[i]] = i
	max_pos = 0
	ans = 0
	for i in range(m):
		p = pos[b[i]]
		if p > max_pos:
			ans += (p - i) * 2
			max_pos = p
		ans += 1
	print(ans)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	pos = {}
	for i in range(n):
		pos[a[i]] = i
	left = set(b)
	time = 0
	last = -1
	llast = set()
	for i in range(m):
		if b[i] in llast:
			llast.remove(b[i])
			time += 1
			continue
		if a[last + 1] == b[i]:
			time += 2 * len(llast) + 1
			last += 1
			left.remove(b[i])
		else:
			time += 2 * (pos[b[i]] - last - 1 + len(llast)) + 1
			left.remove(b[i])
			for j in range(last + 1, pos[b[i]]):
				llast.add(a[j])
			last = pos[b[i]]
	print(time)


n = int(input())
l = []
s = []
for i in range(n):
	m = input()
	x = [i for i in input().split()]
	a = {x[i]: i for i in range(len(x))}
	l.append(a)
	y = input()
	b = [i for i in y.split()]
	s.append(b)
for i in range(len(l)):
	max_ind = 0
	total = 0
	diff = 0
	for j in s[i]:
		ind = l[i][j]
		if max_ind > ind:
			total += 1
			diff += 1
		else:
			cur_ind = ind - diff
			total += 2 * cur_ind + 1
			max_ind = ind
			diff += 1
	print(total)


from sys import stdin, setrecursionlimit
from collections import deque
from math import sqrt, floor, ceil, log, log2, log10, pi, gcd, sin, cos, asin

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

def fi():
	return float(stdin.readline())

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

def fmi():
	return map(float, stdin.readline().split())

def li():
	return list(mi())

def lsi():
	x = list(stdin.readline())
	x.pop()
	return x

def si():
	return stdin.readline()
mod = 1000000007
res = ['YES', 'NO']
t_c = ii()
for _ in range(t_c):
	(n, m) = mi()
	a = li()
	b = li()
	pos = [0] * (n + 1)
	for i in range(n):
		pos[a[i]] = i
	mx = s = 0
	for j in range(m):
		x = max(0, pos[b[j]] - j)
		if pos[b[j]] < mx:
			x = 0
		else:
			mx = pos[b[j]]
		s += 2 * x + 1
	print(s)


def test(n, m):
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	c = [0] * (n + 1)
	for i in range(n):
		c[a[i]] = i
	j = c[b[0]]
	k = 2 * j + 1
	cc = 1
	for i in range(1, m):
		jj = c[b[i]]
		if jj < j:
			k += 1
			cc += 1
		else:
			j = jj
			k += 2 * (j - i) + 1
	return k
for i in range(int(input())):
	(n, m) = map(int, input().split())
	print(test(n, m))


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = [int(i) for i in input().split()]
	b = [int(i) for i in input().split()]
	positions = {}
	for (ind, num) in enumerate(a):
		positions[num] = ind
	where_we_got_to = 0
	num_of_deleted_items = 0
	amount_of_time = 0
	for num in b:
		if positions[num] <= where_we_got_to:
			amount_of_time += 1
		else:
			where_we_got_to = positions[num] - 1
			amount_of_time += 2 * (positions[num] - num_of_deleted_items) + 1
		num_of_deleted_items += 1
	print(amount_of_time)


q = int(input())
for _ in range(q):
	(n, m) = map(int, input().split())
	arrN = list(map(int, input().split()))
	arrM = list(map(int, input().split()))
	dic = {}
	for (i, num) in enumerate(arrN):
		dic[num] = i
	d = 0
	ma = 0
	s = 0
	for num in arrM:
		if dic[num] <= ma:
			s += 1
		else:
			ma = dic[num]
			s = s + 2 * (dic[num] - d) + 1
		d += 1
	print(s)


import sys
T = int(sys.stdin.readline().strip())
for t in range(0, T):
	(n, m) = list(map(int, sys.stdin.readline().strip().split()))
	a = list(map(int, sys.stdin.readline().strip().split()))
	b = list(map(int, sys.stdin.readline().strip().split()))
	d = [0] * (n + 1)
	ans = 0
	x = 0
	for i in range(0, n):
		d[a[i]] = i
	for j in range(0, m):
		h = d[b[j]]
		if h >= x:
			ans = ans + 2 * (h - j) + 1
			x = h
		else:
			ans = ans + 1
	print(ans)


q = int(input())
t = 1
vis = [0] * 300000
for i in range(q):
	(n, m) = [int(x) for x in input().split()]
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	arr = 0
	i = 0
	k = 0
	for item in b:
		if vis[item] == t:
			arr += 1
			k -= 1
			continue
		while i < n:
			vis[a[i]] = t
			if a[i] == item:
				arr += 2 * k + 1
				i += 1
				break
			i += 1
			k += 1
	print(arr)
	t += 1


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


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	ind = [0 for _ in range(n + 1)]
	buff = [0 for _ in range(n + 1)]
	f = 1
	for i in range(n):
		ind[a[i]] = f
		f += 1
	g = 0
	t = 0
	for i in range(m):
		if ind[b[i]] < g:
			t += 1
		else:
			g = ind[b[i]]
			t += 2 * (g - i - 1) + 1
	print(t)


from collections import defaultdict
t = int(input())
for _ in range(t):
	(n, m) = [int(i) for i in input().split()]
	a = [int(i) for i in input().split()]
	b = [int(i) for i in input().split()]
	Dict = defaultdict(int)
	count = ans = start = 0
	for i in range(m):
		x = b[i]
		if Dict[b[i]] == 0:
			while start < n and a[start] != x:
				temp = a[start]
				count += 1
				start += 1
				Dict[temp] = 1
			ans += 2 * count + 1
			start += 1
		else:
			ans += 1
			count -= 1
	print(ans)


t = int(input())
for _ in range(t):
	(n, m) = list(map(int, input().split()))
	s = list(map(int, input().split()))
	a = list(map(int, input().split()))
	done = set()
	total = 0
	start = 0
	ad = 0
	i = 0
	for j in range(0, n):
		if s[j] == a[i]:
			total += (j - ad) * 2 + 1
			ad += 1
			i += 1
			while i < m and a[i] in done:
				i += 1
				total += 1
				ad += 1
			if i == m:
				break
		else:
			done.add(s[j])
	print(total)


import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__

def solve():
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	d = {}
	for i in range(n):
		d[a[i]] = i + 1
	max_ = 0
	used = 0
	ans = 0
	for bi in b:
		i = d[bi]
		if i > max_:
			max_ = i
			ans += 2 * (i - used - 1) + 1
			used += 1
		else:
			ans += 1
			used += 1
	print(ans)
t = int(input())
for i in range(t):
	solve()


import sys, os, io

def rs():
	return sys.stdin.readline().rstrip()

def ri():
	return int(sys.stdin.readline())

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

def ws(s):
	sys.stdout.write(s + '\n')

def wi(n):
	sys.stdout.write(str(n) + '\n')

def wia(a):
	sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
import math, datetime, functools, itertools, operator, bisect
from collections import deque, defaultdict, OrderedDict
import collections

def main():
	starttime = datetime.datetime.now()
	if os.path.exists('input.txt'):
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	for _ in range(ri()):
		(n, m) = ria()
		a = ria()
		b = ria()
		d = {}
		b = deque(b)
		ans = 0
		c = 0
		i = 0
		while c < m:
			if b[0] in d:
				b.popleft()
				c += 1
				ans += 1
				if c == m:
					break
				continue
			if c < m and a[i] != b[0]:
				d[a[i]] = 1
			else:
				if c == m:
					break
				b.popleft()
				ans += 2 * (i - c) + 1
				c += 1
			i += 1
		print(ans)
	endtime = datetime.datetime.now()
	time = (endtime - starttime).total_seconds() * 1000
	if os.path.exists('input.txt'):
		print('Time:', time, 'ms')

class FastReader(io.IOBase):
	newlines = 0

	def __init__(self, fd, chunk_size=1024 * 8):
		self._fd = fd
		self._chunk_size = chunk_size
		self.buffer = io.BytesIO()

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size))
			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, size=-1):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size))
			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()

class FastWriter(io.IOBase):

	def __init__(self, fd):
		self._fd = fd
		self.buffer = io.BytesIO()
		self.write = self.buffer.write

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

class FastStdin(io.IOBase):

	def __init__(self, fd=0):
		self.buffer = FastReader(fd)
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

class FastStdout(io.IOBase):

	def __init__(self, fd=1):
		self.buffer = FastWriter(fd)
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.flush = self.buffer.flush
sys.stdin = FastStdin()
sys.stdout = FastStdout()
main()


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	x = [-1] * (n + 1)
	for i in range(m):
		x[b[i]] = i
	j = m
	for i in range(1, n + 1):
		if x[i] < 0:
			x[i] = j
			j += 1
	a = list(map(lambda y: x[y], a))
	c = [-1] * n
	for i in range(n):
		c[a[i]] = i
	maxc = -1
	t = 0
	for i in range(m):
		if c[i] < maxc:
			t += 1
		else:
			t += 2 * (c[i] - i) + 1
			maxc = c[i]
	print(t)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	d = {v: i for (i, v) in enumerate(a)}
	ans = 0
	last = -1
	sent_so_far = 0
	for i in range(m):
		x = d[b[i]]
		if x > last:
			last = x
			ans += 2 * (x - sent_so_far) + 1
			sent_so_far += 1
		else:
			ans += 1
			sent_so_far += 1
	print(ans)


import sys
readline = sys.stdin.readline
T = int(readline())
Ans = [None] * T
for qu in range(T):
	(N, M) = map(int, readline().split())
	A = list(map(int, readline().split()))
	B = list(map(int, readline().split()))
	A.reverse()
	res = 0
	seen = set()
	for b in B:
		res += 1
		if b in seen:
			seen.remove(b)
			continue
		res += 2 * len(seen)
		while A[-1] != b:
			seen.add(A.pop())
			res += 2
		A.pop()
	Ans[qu] = res
print('\n'.join(map(str, Ans)))


from collections import defaultdict

def case():
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	index = defaultdict(int)
	for i in range(n):
		index[a[i]] = i
	depth = -1
	time = 0
	for i in range(m):
		if index[b[i]] > depth:
			time += 2 * (index[b[i]] - i) + 1
			depth = index[b[i]]
		else:
			time += 1
	print(time)
for _ in range(int(input())):
	case()


import sys
from collections import defaultdict
t = 1
t = int(input())
for i in range(t):
	(n, m) = list(map(int, sys.stdin.readline().strip().split()))
	a = list(map(int, sys.stdin.readline().strip().split()))
	b = list(map(int, sys.stdin.readline().strip().split()))
	d = defaultdict(int)
	k = 0
	for j in a:
		d[j] = k
		k += 1
	x = 0
	op = 0
	c = 0
	for j in b:
		if d[j] <= x:
			op = op + 1
		else:
			x = d[j]
			op = op + (d[j] - c) * 2 + 1
		c = c + 1
	print(op)


t = int(input())
for i in range(t):
	(n, m) = input().split()
	n = int(n)
	m = int(m)
	a = [0] * n
	p = [0] * n
	a = input().split()
	for j in range(n):
		p[int(a[j]) - 1] = j
	mx = -1
	ans = 0
	b = [0] * n
	b = input().split()
	for j in range(m):
		b[j] = p[int(b[j]) - 1]
		if mx < b[j]:
			mx = b[j]
			ans += (b[j] - j) * 2 + 1
		else:
			ans += 1
	print(ans)


t = int(input())
for i in range(t):
	(n, m) = map(int, input().split())
	a = [int(j) for j in input().split()]
	b = [int(j) for j in input().split()]
	maxIndex = -1
	out = 0
	qwe = 0
	gg = {}
	for ii in range(n):
		gg[a[ii]] = ii
	for j in b:
		ind = gg[j]
		if ind < maxIndex:
			out += 1
		else:
			maxIndex = ind
			out += (ind - qwe) * 2 + 1
		qwe += 1
	print(out)


t = int(input())
for i in range(t):
	s = list(map(int, input().split()))
	n = s[0]
	m = s[1]
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	d = {}
	for i in range(n):
		d[a[i]] = i
	t = 0
	last = -1
	p = 0
	for i in range(m):
		x = d[b[i]]
		if x > last:
			t += 2 * (x - p) + 1
			last = x
			p += 1
		else:
			t += 1
			p += 1
	print(t)


ip = lambda : map(int, input().split())
t = int(input())
for ti in range(t):
	(m, n) = ip()
	stk = list(ip())
	ords = list(ip())
	s = set()
	ans = 0
	for i in ords:
		if i not in s:
			while stk[0] != i:
				s.update({stk.pop(0)})
			ans += 2 * len(s) + 1
			stk.pop(0)
		else:
			ans += 1
			s.remove(i)
	print(ans)


for i in range(int(input())):
	(n, m) = [int(x) for x in input().split()]
	data_est = [int(x) for x in input().split()]
	data_nado = [int(x) for x in input().split()]
	data = [0] * (n + 1)
	for j in range(n):
		data[data_est[j]] = j
	maxx = -1
	count = m
	for j in range(m):
		d1 = data_nado[j]
		d = data[d1]
		if d >= maxx:
			maxx = d
			count += (d - j) * 2
	print(count)


def solveOne():
	pos = {}
	for (i, val) in enumerate(a):
		pos[val] = i
	mx = -1
	taken = 0
	ret = 0
	for i in b:
		at = pos[i]
		if at > mx:
			ret += (at - taken) * 2 + 1
			mx = at
		else:
			ret += 1
		taken += 1
	return ret
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	print(solveOne())


for t in range(int(input())):
	(alen, blen) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	se = set()
	i = 0
	j = 0
	time = 0
	while i < blen:
		if b[i] in se:
			se.remove(b[i])
			time += 1
			i += 1
			continue
		while j < alen:
			if b[i] != a[j]:
				se.add(a[j])
				j += 1
			else:
				time += 2 * len(se) + 1
				j += 1
				i += 1
				break
	print(time)


from functools import reduce
import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import *
from io import BytesIO, IOBase
input = lambda : sys.stdin.readline().rstrip('\r\n')

def value():
	return tuple(map(int, input().split()))

def arr():
	return [int(i) for i in input().split()]

def sarr():
	return [int(i) for i in input()]

def starr():
	return [str(x) for x in input().split()]

def inn():
	return int(input())

def svalue():
	return tuple(map(str, input().split()))

def parr():
	return [value() for i in range(n)]
mo = 1000000007
for _ in range(inn()):
	(n, m) = value()
	a = arr()
	b = arr()
	i = 0
	d = defaultdict(int)
	ans = 0
	j = 0
	while i < n and j < m:
		if b[j] in d:
			ans += 1
			j += 1
		else:
			while i < n and a[i] != b[j]:
				d[a[i]] += 1
				i += 1
			ans += 2 * (i - j) + 1
			i += 1
			j += 1
	ans += m - j
	print(ans)


x = int(input())
for i in range(x):
	a = input().split(' ')
	y = list(map(int, input().split(' ')))
	z = list(map(int, input().split(' ')))
	q = [0] * len(y)
	for i in range(len(y)):
		q[y[i] - 1] = i + 1
	m = q[z[0] - 1]
	t = 0
	p = 0
	for j in range(len(z)):
		if q[z[j] - 1] < m:
			t += 1
			p += 1
		else:
			m = q[z[j] - 1]
			t += (q[z[j] - 1] - p) * 2 - 1
			p += 1
	print(t)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	topmost = set()
	a = iter(map(int, input().split()))
	b = map(int, input().split())
	ans = 0
	for bi in b:
		if bi in topmost:
			k = 0
			topmost.remove(bi)
		else:
			k = len(topmost)
			for ai in a:
				if ai == bi:
					break
				topmost.add(ai)
				k += 1
			else:
				raise ValueError(f'No {bi} in a')
		ans += 2 * k + 1
	print(ans)


import sys

def debug(*args):
	print(*args, file=sys.stderr)
t = int(input())
for _ in range(t):
	(m, n) = list(map(int, input().split()))
	an = list(map(int, input().split()))
	bm = list(map(int, input().split()))
	bm_set = set(bm)
	seen = set()
	ans = 0
	i = 0
	j = 0
	while len(bm) > 0:
		temp = bm.pop(0)
		if temp in seen:
			ans += 1
			j += 1
		while temp not in seen:
			if temp == an[i]:
				ans += 2 * (i - j) + 1
				j += 1
				seen.add(temp)
			elif an[i] in bm_set:
				seen.add(an[i])
			i += 1
	print(ans)


kl = int(input())
for l in range(kl):
	(n, m) = [int(i) for i in input().split()]
	ind = [0 for i in range(0, n + 1)]
	a = [0 for i in range(n)]
	sc = 1
	for i in input().split():
		i = int(i)
		ind[i] = sc
		sc += 1
	mm = 0
	ssc = 0
	scp = 0
	for i in input().split():
		i = int(i)
		if ind[i] > mm:
			ssc = ssc + 2 * (ind[i] - scp - 1) + 1
			scp += 1
			mm = ind[i]
		else:
			ssc += 1
			scp += 1
	print(ssc)


t = int(input())
for i in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	c = [0] * n
	for j in range(n):
		c[a[j] - 1] = j
	Mindex = 0
	ans = 0
	for h in range(m):
		if c[b[h] - 1] > Mindex:
			ans += 2 * c[b[h] - 1] + 1 - 2 * h
			Mindex = c[b[h] - 1]
		else:
			ans += 1
	print(ans)


from __future__ import division, print_function
import os, sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip

def ii():
	return int(input())

def si():
	return input()

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

def li():
	return list(mi())

def gcd(x, y):
	while y:
		(x, y) = (y, x % y)
	return x

def main():
	for i in range(ii()):
		(n, m) = mi()
		a = li()
		b = li()
		c = [0] * 100005
		for i in range(n):
			c[a[i]] = i
		ans = c[b[0]] * 2 + 1
		f = 1
		p = c[b[0]]
		for i in range(1, m):
			if c[b[i]] < p:
				f += 1
				ans += 1
			else:
				ans = ans + (c[b[i]] - f) * 2 + 1
				p = c[b[i]]
				f += 1
		print(ans)
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')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = [0] * (n + 1)
	j = 1
	for i in input().split():
		a[int(i)] = j
		j += 1
	count = 0
	curpop = 0
	maxdepth = 0
	for i in input().split():
		if a[int(i)] > maxdepth:
			maxdepth = a[int(i)]
			count += 2 * (maxdepth - curpop) - 1
		else:
			count += 1
		curpop += 1
	print(count)


import sys

def minp():
	return sys.stdin.readline().strip()

def mint():
	return int(minp())

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

def get(a, x):
	r = 0
	while x >= 0:
		r += a[x]
		x = (x & x + 1) - 1
	return r

def add(a, x, v):
	while x < len(a):
		a[x] += v
		x |= x + 1

def solve():
	(n, m) = mints()
	a = list(mints())
	w = [0] * (n + 1)
	f = [0] * n
	g = [0] * n
	for i in range(n):
		w[a[i]] = i
		add(f, i, 1)
	s = 0
	r = 0
	for j in mints():
		wj = w[j]
		if g[wj] == 1:
			r += 1
			add(f, wj, -1)
		else:
			add(f, wj, -1)
			r += 2 * get(f, wj) + 1
			for i in range(s, wj):
				g[i] = 1
			s = wj
	print(r)
for i in range(mint()):
	solve()


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	a_index = [0] * (n + 1)
	for i in range(n):
		a_index[a[i]] = i + 1
	ans = 0
	r = 0
	c = set()
	for j in range(m):
		if b[j] in c:
			ans += 1
		else:
			ans += (a_index[b[j]] - j) * 2 - 1
			for i in range(r, a_index[b[j]]):
				c.add(a[i])
				r = i
	print(ans)


for i in range(int(input())):
	(n, m) = map(int, input().split())
	presents = list(map(int, input().split()))
	send = list(map(int, input().split()))
	lst = [-1] * (10 ** 5 + 1)
	(ans, a, b) = (0, 0, 0)
	for j in send:
		if lst[j] == 1:
			ans += 1
			b += 1
		else:
			for k in range(a, n):
				if presents[k] == j:
					ans += 2 * (k - b) + 1
					a = k + 1
					b += 1
					break
				else:
					lst[presents[k]] = 1
	print(ans)


import math, string, itertools, fractions, heapq, collections, re, array, bisect, sys, copy, functools
inf = 10 ** 20
eps = 1.0 / 10 ** 10
mod = 10 ** 9 + 7
mod2 = 998244353
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]

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

def LLI():
	return [list(map(int, l.split())) for l in sys.stdin.readlines()]

def LI_():
	return [int(x) - 1 for x in sys.stdin.readline().split()]

def LF():
	return [float(x) for x in sys.stdin.readline().split()]

def LS():
	return sys.stdin.readline().split()

def I():
	return int(sys.stdin.readline())

def F():
	return float(sys.stdin.readline())

def S():
	return input()

def pf(s):
	return print(s, flush=True)

def pe(s):
	return print(str(s), file=sys.stderr)

def JA(a, sep):
	return sep.join(map(str, a))

def JAA(a, s, t):
	return s.join((t.join(map(str, b)) for b in a))

def IF(c, t, f):
	return t if c else f

def YES(c):
	return IF(c, 'YES', 'NO')

def Yes(c):
	return IF(c, 'Yes', 'No')

def main():
	t = I()
	rr = []
	for _ in range(t):
		(n, m) = LI()
		a = LI()
		b = LI()
		d = collections.defaultdict(int)
		for (i, c) in enumerate(a):
			d[c] = i
		r = m
		k = 0
		for (i, c) in enumerate(b):
			t = d[c]
			if t <= k:
				continue
			u = t - i
			r += u * 2
			k = t
		rr.append(r)
	return JA(rr, '\n')
print(main())


a = int(input())
for _ in range(a):
	(x, y) = map(int, input().split())
	li1 = list(map(int, input().split()))
	li2 = list(map(int, input().split()))
	li3 = [0] * (x + 1)
	for i in range(x):
		li3[li1[i]] = i
	a = -1
	count = 0
	for i in range(y):
		b = li3[li2[i]]
		if b < a:
			count += 1
		else:
			count += 2 * (b - i) + 1
			a = b
	print(count)


for t in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	c = list(map(int, input().split()))
	(aa, bb) = ([], [])
	for i in range(n):
		aa.append([a[i], i])
	aa.sort()
	b = []
	for i in range(m):
		b.append([c[i], i])
	b.sort()
	visit = [0 for i in range(m)]
	i = 0
	j = 0
	while j != m:
		if aa[i][0] == b[j][0]:
			visit[b[j][1]] = aa[i][1]
			j += 1
		i += 1
	store = 0
	count = 0
	i = 0
	r = 0
	while i < m:
		r = visit[i]
		count += 2 * (r - i) + 1
		while i < m:
			if visit[i] < r:
				count += 1
			elif visit[i] == r:
				count += 0
			else:
				break
			i += 1
	print(count)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	(*a,) = map(int, input().split())
	(*b,) = map(int, input().split())
	pos = [0] * (n + 1)
	last = -1
	for i in range(n):
		pos[a[i]] = i
	ans = 0
	for i in range(m):
		ans += 1
		if pos[b[i]] > last:
			ans += 2 * (pos[b[i]] - i)
			last = pos[b[i]]
	print(ans)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	arr1 = list(map(int, input().split()))
	arr2 = list(map(int, input().split()))
	last = n - 1
	ans = 0
	dic = {}
	for i in range(n):
		dic[arr1[i]] = i
	ans = 2 * dic[arr2[0]] + 1
	last = dic[arr2[0]]
	for i in range(1, m):
		if dic[arr2[i]] < last:
			ans += 1
		else:
			ans += 2 * (dic[arr2[i]] - i) + 1
			last = dic[arr2[i]]
	print(ans)


for _ in range(int(input())):
	(N, M) = map(int, input().split())
	L = list(map(int, input().split()))
	S = list(map(int, input().split()))
	Hash = [0] * (N + 1)
	for i in range(1, N + 1):
		Hash[L[i - 1]] = i
	m = 1
	ans = 0
	for i in range(M):
		if Hash[S[i]] <= m:
			ans = ans + 1
		else:
			ans += 2 * (Hash[S[i]] - (i + 1)) + 1
		x = Hash[S[i]]
		if x >= m:
			m = x
	print(ans)


T = int(input())
for i in range(T):
	(n, m) = list(map(int, input().split()))
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	ind = [0] * (n + 1)
	for i in range(n):
		ind[a[i]] = i
	ma = ind[b[0]]
	ans = 2 * ma + 1
	for j in range(1, m):
		inde = ind[b[j]]
		if inde < ma:
			ans += 1
		else:
			ma = inde
			ans += 2 * (inde - j) + 1
	print(ans)


t = int(input())
for case in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	p = [0] * (n + 1)
	ans = 0
	ct = 0
	y = 0
	for j in range(m):
		if p[b[j]] == 1:
			ct = ct - 1
			ans = ans + 1
		else:
			while p[b[j]] == 0:
				p[a[y]] = 1
				y = y + 1
				ct = ct + 1
			ct -= 1
			ans += ct * 2 + 1
	print(ans)


MOD = 1000000007
ii = lambda : int(input())
si = lambda : input()
dgl = lambda : list(map(int, input()))
f = lambda : map(int, input().split())
il = lambda : list(map(int, input().split()))
ls = lambda : list(input())
for _ in range(ii()):
	(n, m) = f()
	st = il()
	d = dict(((st[i], i) for i in range(n)))
	gfts = il()
	(mx, tm) = (0, 0)
	for i in range(m):
		if d[gfts[i]] > mx:
			tm += 2 * (d[gfts[i]] - i) + 1
			mx = d[gfts[i]]
		else:
			tm += 1
	print(tm)


import sys
t = int(sys.stdin.readline())
for _ in range(t):
	sys.stdin.readline()
	a = list(map(int, sys.stdin.readline().split()))
	b = list(map(int, sys.stdin.readline().split()))
	pos = [0] * len(a)
	for i in range(len(a)):
		pos[a[i] - 1] = i
	total = 0
	plusloin = -1
	for i in range(len(b)):
		if pos[b[i] - 1] > plusloin:
			total += 2 * (pos[b[i] - 1] - i) + 1
			plusloin = pos[b[i] - 1]
		else:
			total += 1
	print(total)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(zip(map(int, input().split()), [i for i in range(n)]))
	b = list(zip(map(int, input().split()), [i for i in range(m)]))
	a.sort(key=lambda x: x[0])
	b.sort(key=lambda x: x[0])
	(i, j) = (0, 0)
	while i != n and j != m:
		if a[i][0] == b[j][0]:
			a[i] = [b[j][1], a[i][1]]
			j += 1
		else:
			a[i] = [100001, a[i][1]]
		i += 1
	while i != n:
		a[i] = [100001, a[i][1]]
		i += 1
	a.sort(key=lambda x: x[1])
	(k, cnt, mn) = (0, 0, 100001)
	for i in range(len(a)):
		if a[len(a) - i - 1][0] != 100001:
			if a[len(a) - i - 1][0] < mn:
				mn = a[len(a) - i - 1][0]
				k += 2 * (a[len(a) - i - 1][1] - a[len(a) - i - 1][0])
			k += 1
			cnt += 1
	print(k)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	stack = [int(x) for x in input().split()]
	order = [int(x) for x in input().split()]
	seen = set()
	res = 0
	stack_ptr = 0
	for present in order:
		if present in seen:
			res += 1
			seen.remove(present)
		else:
			k = len(seen)
			while stack[stack_ptr] != present:
				seen.add(stack[stack_ptr])
				k += 1
				stack_ptr += 1
			stack_ptr += 1
			res += 2 * k + 1
	print(res)


t = int(input())
while t:
	(n, m) = map(int, input().split())
	a = input().split()
	b = input().split()
	for i in range(n):
		a[i] = int(a[i])
	for i in range(m):
		b[i] = int(b[i])
	index = [0 for i in range(10 ** 5 + 1)]
	visited = [0 for i in range(10 ** 5 + 1)]
	for i in range(n):
		index[a[i]] = i
	max_index = 0
	ans = 0
	for i in range(m):
		if index[b[i]] <= max_index:
			ans += 1
		else:
			ans += 2 * (index[b[i]] - i) + 1
		max_index = max(max_index, index[b[i]])
	print(ans)
	t -= 1


import sys, math
MOD = 10 ** 9 + 7
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	for i in range(n):
		a[i] -= 1
	for i in range(m):
		b[i] -= 1
	p = [-1 for i in range(n)]
	for i in range(n):
		p[a[i]] = i
	(ans, prev) = (0, -1)
	for i in range(m):
		if p[b[i]] > prev:
			ans += 2 * abs(p[b[i]] - i) + 1
		else:
			ans += 1
		prev = max(prev, p[b[i]])
	print(ans)


def px(a):
	d = [0] * (max(a) + 1)
	for (i, v) in enumerate(a):
		d[v] = i
	return d

def solve(n, m, a, b):
	d = px(a)
	t = 0
	p = -1
	x = 0
	for i in b:
		if d[i] > p:
			p = d[i]
			t += 2 * (p - x) + 1
			x += 1
		else:
			t += 1
			x += 1
	return t

def main():
	for _ in range(int(input())):
		(n, m) = list(map(int, input().split()))
		a = list(map(int, input().split()))
		b = list(map(int, input().split()))
		print(solve(n, m, a, b))
main()


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	A = list(map(int, input().split()))
	B = list(map(int, input().split()))
	ans = 0
	idx = [0] * (n + 1)
	vst = [False] * n
	for i in range(n):
		idx[A[i]] = i
	midx = -1
	cnt = 0
	for b in B:
		if idx[b] < midx:
			ans += 1
		else:
			ans += (idx[b] - cnt) * 2 + 1
			midx = idx[b]
		cnt += 1
	print(ans)


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	ind = {}
	for i in range(n):
		ind[a[i]] = i
	c = m
	curind = 0
	while curind < m:
		cur = ind[b[curind]]
		c += cur - curind << 1
		curind += 1
		while curind < m and ind[b[curind]] < cur:
			curind += 1
	print(c)


import math, sys
from collections import Counter, defaultdict, deque
from sys import stdin, stdout
input = stdin.readline
lili = lambda : list(map(int, sys.stdin.readlines()))
li = lambda : list(map(int, input().split()))
I = lambda : int(input())
S = lambda : input().strip()
for i in range(I()):
	(n, m) = li()
	a = li()
	b = li()
	d = defaultdict(int)
	c = 0
	k = 0
	for i in range(0, m):
		if b[i] in d:
			c += 1
			del d[b[i]]
		else:
			c = c + 2 * len(d)
			for j in range(k, n):
				if a[j] == b[i]:
					c += 1
					k = j + 1
					break
				else:
					d[a[j]] = 0
					c += 2
	print(c)


import sys

class CStackOfPresents:

	def solve(self):
		for _ in range(int(input())):
			(n, m) = [int(_) for _ in input().split()]
			a = [int(_) for _ in input().split()]
			b = [int(_) for _ in input().split()]
			ordered = [0] * (n + 1)
			position = [0] * (n + 1)
			for i in range(n):
				position[a[i]] = i
			ans = 0
			cur = 0
			for i in range(m):
				if ordered[b[i]]:
					ans += 1
				else:
					ans += 2 * (position[b[i]] - i) + 1
					for j in range(cur, position[b[i]] + 1):
						ordered[a[j]] = 1
					cur = position[b[i]] + 1
			print(ans)
solver = CStackOfPresents()
input = sys.stdin.readline
solver.solve()


t = int(input())
for i in range(t):
	(n, m) = map(int, input().split())
	lst1 = list(map(int, input().split()))
	lst2 = list(map(int, input().split()))
	Dict = {}
	for j in range(n):
		ele = lst1[j]
		Dict[ele] = j
	ans = 0
	Max = -float('inf')
	for k in range(m):
		j = lst2[k]
		index = Dict[j]
		if index < Max:
			ans = ans + 1
		else:
			Max = index
			ans = ans + 2 * (index - k) + 1
	print(ans)


from collections import deque
for _ in range(int(input())):
	input()
	have = []
	for (i, elem) in enumerate(input().split()):
		have.append((i, int(elem) - 1))
	have.sort(key=lambda x: x[1])
	massive = deque((int(i) - 1 for i in input().split()))
	counter = 0
	taken = 0
	maxx = -1
	for i in massive:
		if have[i][0] < maxx:
			counter += 1
			taken += 1
		else:
			maxx = have[i][0]
			counter += 2 * (have[i][0] - taken) + 1
			taken += 1
	print(counter)


from sys import stdin, stdout

class SOLVE:

	def solve(self):
		R = stdin.readline
		W = stdout.write
		ans = []
		for i in range(int(R())):
			(n, m) = [int(x) for x in R().split()]
			a = [int(x) for x in R().split()]
			b = [int(x) for x in R().split()]
			pos = {}
			for j in range(n):
				pos[a[j]] = j
			time = 0
			tmp_pos = -1
			for j in range(m):
				if pos[b[j]] <= tmp_pos:
					time += 1
				else:
					time += 2 * (pos[b[j]] - j) + 1
				tmp_pos = max(tmp_pos, pos[b[j]])
			ans.append(str(time))
		W('\n'.join(ans))
		return 0

def main():
	s = SOLVE()
	s.solve()
main()


import sys
t = int(sys.stdin.readline().rstrip())

def main():
	for _ in range(t):
		(n, m) = map(int, sys.stdin.readline().split())
		(*a,) = map(int, sys.stdin.readline().split())
		(*b,) = map(int, sys.stdin.readline().split())
		ind = [None] * (n + 1)
		for i in range(n):
			ind[a[i]] = i
		cnt = 0
		rightest_ind = -1
		for i in range(m):
			present = b[i]
			if ind[present] < rightest_ind:
				cnt += 1
			else:
				k = ind[present] - i
				cnt += k * 2 + 1
				rightest_ind = ind[present]
		yield cnt
ans = main()
print(*ans, sep='\n')


def DEBUG():
	import sys
	sys.stdin = open('/dev/tty')
	import pdb
	pdb.set_trace()

def prog(n, m, a, b):
	pos = [-1] * (n + 1)
	for i in range(n):
		pos[a[i]] = i
	lst = -1
	ans = 0
	for i in range(m):
		if lst > pos[b[i]]:
			ans += 1
		elif lst < pos[b[i]]:
			ans += 1 + 2 * (pos[b[i]] - i)
		lst = max(lst, pos[b[i]])
	return ans
t = int(input())
while t > 0:
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	print(prog(n, m, a, b))
	t -= 1


from collections import defaultdict
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	ai = list(map(int, input().split()))
	bi = list(map(int, input().split()))
	dictt = defaultdict(int)
	for i in range(0, len(ai)):
		dictt[ai[i]] = i
	stack = dictt[bi[0]]
	ans = 2 * stack + 1
	t = 1
	i = 1
	while i < len(bi):
		if dictt[bi[i]] > stack:
			stack = dictt[bi[i]]
			ans += 2 * (stack - t) + 1
			t += 1
		else:
			ans += 1
			t += 1
		i += 1
	print(ans)


for _ in range(int(input())):
	(n, m) = list(map(int, input().split()))
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	index = [0] * 100001
	for i in range(n):
		index[a[i]] = i
	sorted_ptr = 0
	moves = 0
	prevremoved = 0
	removed = set()
	for i in range(m):
		if index[b[i]] <= sorted_ptr:
			moves += 1
			prevremoved += 1
			removed.add(b[i])
		else:
			moves += 2 * abs(sorted_ptr + 1 - prevremoved)
			while a[sorted_ptr] != b[i]:
				sorted_ptr += 1
				if a[sorted_ptr] == b[i]:
					moves += 1
					prevremoved += 1
					break
				moves += 2
	print(moves)


from sys import stdin, stdout

def solve(n, m, a, b):
	out = stdout.write
	d = {}
	for i in range(n):
		d[a[i]] = i
	mxi = 0
	ans = 0
	for i in range(m):
		if d[b[i]] <= mxi:
			ans += 1
		else:
			ans += 2 * (d[b[i]] - i) + 1
			mxi = d[b[i]]
	out(str(ans) + '\n')

def main():
	inp = stdin.readline
	for _ in range(int(inp())):
		(n, m) = map(int, inp().split())
		a = list(map(int, inp().split()))
		b = list(map(int, inp().split()))
		solve(n, m, a, b)
main()


pos = [0 for i in range(int(10 ** 6) + 10)]
tt = int(input())
for i in range(tt):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	for i in range(n):
		pos[a[i]] = i
	ans = 0
	mx = -1
	for i in range(m):
		if pos[b[i]] < mx:
			ans += 1
		else:
			mx = pos[b[i]]
			ans += 2 * (mx - i) + 1
	print(ans)


from sys import stdin
for _ in range(int(stdin.readline())):
	(n, m) = map(int, stdin.readline().split())
	arrn = list(map(int, stdin.readline().split()))
	arrm = list(map(int, stdin.readline().split()))
	time = 0
	maxind = -1
	d = {}
	for i in range(n):
		d[arrn[i]] = i
	count = 0
	for i in range(m):
		k = d[arrm[i]]
		if k <= maxind:
			time += 1
		else:
			time += 2 * (k - count) + 1
			maxind = k
		count += 1
	print(time)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	d = {a[i]: i for i in range(n)}
	presents_popped = 0
	pointer = 0
	time = 0
	for present in b:
		if d[present] > pointer:
			time += (d[present] - presents_popped) * 2 + 1
			pointer = d[present]
		else:
			time += 1
		presents_popped += 1
	print(time)


def solve():
	t = int(input())
	for _ in range(t):
		s1 = input()
		(n, m) = map(int, s1.split())
		s2 = input()
		a = list(map(int, s2.split()))
		s3 = input()
		b = list(map(int, s3.split()))
		count = 0
		index = [0] * (max(a) + 1)
		for i in range(n):
			index[a[i]] = i
		(sum_, temp) = (0, 0)
		for i in range(m):
			idx = index[b[i]]
			if idx >= temp:
				temp = idx
				sum_ += 2 * (idx - count) + 1
				count += 1
			else:
				count += 1
				sum_ += 1
		print(sum_)
solve()


from __future__ import division, print_function
import os, sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip

def ii():
	return int(input())

def si():
	return input()

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

def msi():
	return map(str, input().strip().split(' '))

def li():
	return list(mi())

def dmain():
	sys.setrecursionlimit(1000000)
	threading.stack_size(1024000)
	thread = threading.Thread(target=main)
	thread.start()
import sys
input = sys.stdin.readline
scan_int = lambda : int(input())
scan_string = lambda : input().rstrip()
read_list = lambda : list(read())
read = lambda : map(int, input().split())
read_float = lambda : map(float, input().split())

def ceil(x):
	if x != int(x):
		x = int(x) + 1
	return x

def factorial(x, m):
	val = 1
	while x > 0:
		val = val * x % m
		x -= 1
	return val

def fact(x):
	val = 1
	while x > 0:
		val *= x
		x -= 1
	return val

def swaparr(arr, a, b):
	temp = arr[a]
	arr[a] = arr[b]
	arr[b] = temp

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

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

def is_integer(n):
	return math.ceil(n) == math.floor(n)

def nCr(n, k):
	if k > n:
		return 0
	if k > n - k:
		k = n - k
	res = 1
	for i in range(k):
		res = res * (n - i)
		res = res / (i + 1)
	return int(res)

def primefs(n):
	primes = {}
	while n % 2 == 0 and n > 0:
		primes[2] = primes.get(2, 0) + 1
		n = n // 2
	for i in range(3, int(n ** 0.5) + 2, 2):
		while n % i == 0 and n > 0:
			primes[i] = primes.get(i, 0) + 1
			n = n // i
	if n > 2:
		primes[n] = primes.get(n, 0) + 1
	return primes

def power(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def swap(a, b):
	temp = a
	a = b
	b = temp
	return (a, b)

def find(x, link):
	p = x
	while p != link[p]:
		p = link[p]
	while x != p:
		nex = link[x]
		link[x] = p
		x = nex
	return p

def union(x, y, link, size):
	x = find(x, link)
	y = find(y, link)
	if size[x] < size[y]:
		(x, y) = swap(x, y)
	if x != y:
		size[x] += size[y]
		link[y] = x

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

def phi(n):
	result = n
	p = 2
	while p * p <= n:
		if n % p == 0:
			while n % p == 0:
				n = n // p
			result = result * (1.0 - 1.0 / float(p))
		p = p + 1
	if n > 1:
		result = result * (1.0 - 1.0 / float(n))
	return int(result)

def is_prime(n):
	if n == 0:
		return False
	if n == 1:
		return True
	for i in range(2, int(n ** (1 / 2)) + 1):
		if not n % i:
			return False
	return True

def next_prime(n, primes):
	while primes[n] != True:
		n += 1
	return n
MAXN = int(100000.0 + 5)

def spf_sieve():
	spf[1] = 1
	for i in range(2, MAXN):
		spf[i] = i
	for i in range(4, MAXN, 2):
		spf[i] = 2
	for i in range(3, ceil(MAXN ** 0.5), 2):
		if spf[i] == i:
			for j in range(i * i, MAXN, i):
				if spf[j] == j:
					spf[j] = i
spf = [0 for i in range(MAXN)]

def factoriazation(x):
	res = []
	for i in range(2, int(x ** 0.5) + 1):
		while x % i == 0:
			res.append(i)
			x //= i
	if x != 1:
		res.append(x)
	return res

def factors(n):
	res = []
	for i in range(1, int(n ** 0.5) + 1):
		if n % i == 0:
			res.append(i)
			res.append(n // i)
	return list(set(res))

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

def float_array():
	return list(map(float, input().strip().split()))

def str_array():
	return input().strip().split()

def binary_search(low, high, w, h, n):
	while low < high:
		mid = low + (high - low) // 2
		if check(mid, w, h, n):
			low = mid + 1
		else:
			high = mid
	return low

def check(beauty, s, n, count):
	pass
MOD = int(1000000000.0) + 7
CMOD = 998244353
INF = float('inf')
NINF = -float('inf')
from itertools import permutations
import math
import bisect as bis
import random
import sys
import collections as collect

def solve():
	(n, m) = read()
	a = read_list()
	b = read_list()
	book = {}
	last_book = 0
	books_removed = 0
	for i in range(n):
		book[a[i]] = i
	s = 0
	for x in b:
		if book[x] >= last_book:
			last_book = book[x]
			s += 2 * (book[x] - books_removed) + 1
			books_removed += 1
		else:
			s += 1
			books_removed += 1
	print(s)
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')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
for i in range(scan_int()):
	solve()


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	ans = [False for i in range(n + 1)]
	j = 0
	ak = 0
	count = 0
	for i in range(n):
		if j == m:
			break
		ans[a[i]] = True
		if a[i] == b[j]:
			count += 2 * (i - j) + 1
			j += 1
			ak += 1
			while j != m and ans[b[j]] != False:
				j += 1
	count += m - ak
	print(count)


from sys import stdin, stdout
t = int(stdin.readline().strip())
for i in range(t):
	(n, m) = map(int, stdin.readline().strip().split())
	s = list(map(int, stdin.readline().strip().split()))
	s1 = list(map(int, stdin.readline().strip().split()))
	afuera = [False for i in range(n + 5)]
	af = 0
	ans = 0
	ind = 0
	for i in range(m):
		if afuera[s1[i]]:
			ans += 1
			af -= 1
		else:
			for j in range(ind, n):
				if s[j] == s1[i]:
					ind = j + 1
					ans += af * 2 + 1
					break
				else:
					af += 1
					afuera[s[j]] = True
	print(ans)


def solve(stack, presents, n, m):
	indices = {}
	for i in range(n):
		indices[stack[i]] = i
	time = 0
	max_index = -1
	for i in range(m):
		index = indices[presents[i]]
		if index > max_index:
			time += 2 * (index - i) + 1
			max_index = index
		else:
			time += 1
	print(time)

def main():
	t = int(input())
	for i in range(t):
		(n, m) = map(int, input().split())
		stack = list(map(int, input().split()))
		presents = list(map(int, input().split()))
		solve(stack, presents, n, m)
main()


t = int(input())
while t:
	read = input().split()
	n = int(read[0])
	m = int(read[1])
	loc = [0 for i in range(n + 1)]
	dp = [1 for i in range(n + 1)]
	last = [i for i in range(n + 1)]
	read = input().split()
	for i in range(n):
		a = int(read[i])
		loc[a] = i + 1
	ans = 0
	mark = 0
	read = input().split()
	for i in range(m):
		b = int(read[i])
		if loc[b] > mark:
			ans += 2 * (loc[b] - i - 1)
		ans += 1
		mark = max(mark, loc[b])
	print(ans)
	t -= 1


for _ in range(int(input())):
	(n, m) = [int(x) for x in input().split()]
	presents = [int(x) for x in input().split()]
	delivery_order = [int(x) for x in input().split()]
	depth_dict = {x: i for (i, x) in enumerate(presents)}
	depth = 0
	moved = 0
	for (i, delivery) in enumerate(delivery_order):
		current_depth = depth_dict[delivery]
		if current_depth > depth:
			moved += 2 * (current_depth - i)
			depth = current_depth
		moved += 1
	print(moved)


import sys, itertools, math
n = int(sys.stdin.readline())
for _ in range(n):
	(n, m) = [int(i) for i in sys.stdin.readline().strip().split(' ')]
	A = [int(i) for i in sys.stdin.readline().strip().split(' ')]
	B = [int(i) for i in sys.stdin.readline().strip().split(' ')]
	ans = 0
	R = [False] * (n + 1)
	rsize = 0
	ai = 0
	for b in B:
		if R[b]:
			ans += 1
			rsize -= 1
		else:
			for i in range(ai, len(A)):
				if A[i] == b:
					ans += 2 * rsize + 1
					ai = i + 1
					break
				else:
					R[A[i]] = True
					rsize += 1
	print(ans)


from collections import deque
read = lambda : list(map(int, input().split(' ')))
t = int(input())
for i in range(t):
	n_m = read()
	(n, m) = n_m
	arr_n = deque(map(int, input().split(' ')))
	arr_m = read()
	dic1 = dict()
	sum1 = 0
	j = 0
	while j < m:
		flag = 0
		elem1 = arr_m[j]
		if elem1 in dic1:
			flag = 1
			dic1[elem1] -= 1
			sum1 += 1
			if dic1[elem1] == 0:
				del dic1[elem1]
		else:
			temp2 = 0
			for (k, elem2) in enumerate(arr_n):
				if elem1 == elem2:
					flag = 1
					sum1 += 2 * len(dic1) + 1
					temp2 += 1
					break
				else:
					temp2 += 1
					try:
						dic1[elem2] += 1
					except:
						dic1[elem2] = 1
			for x in range(temp2):
				arr_n.popleft()
		if flag:
			j += 1
	print(sum1)


import math
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	arr1 = list(map(int, input().split()))
	arr2 = list(map(int, input().split()))
	d = dict()
	temp = 0
	ans = 0
	for i in range(m):
		if i == 0:
			for j in range(n):
				if arr2[0] == arr1[j]:
					ans = 2 * j + 1
					temp = j
					break
				d[arr1[j]] = 1
		elif arr2[i] in d:
			ans += 1
			continue
		else:
			j = temp
			while j < n:
				if arr1[j] == arr2[i]:
					temp = j
					ans = ans + 2 * (j - i) + 1
					break
				d[arr1[j]] = 1
				j += 1
	print(ans)


import sys

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

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

def oint():
	return int(input())
t = oint()
for _ in range(t):
	(n, m) = rint()
	a = list(rint())
	b = list(rint())
	v = [0] * (n + 1)
	ai = [0] * (n + 1)
	for i in range(n):
		ai[a[i]] = i
	ans = 0
	curi = 0
	for i in range(m):
		if v[b[i]]:
			ans += 1
			continue
		newi = ai[b[i]]
		for j in range(curi, newi):
			v[a[j]] = 1
		ans += 2 * (newi - i) + 1
		curi = newi + 1
	print(ans)


from collections import *
from bisect import *
from math import *
from heapq import *
import sys
input = sys.stdin.readline
t = int(input())
while t:
	t -= 1
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	vis = set()
	r = 0
	p = 0
	j = 0
	for i in range(m):
		if b[i] in vis:
			r += 1
			p += 1
			continue
		while j < n:
			vis.add(a[j])
			if b[i] in vis:
				r += 2 * (j - p) + 1
				p += 1
				flag = 1
				break
			j += 1
	print(r)


t = int(input())
for t in range(t):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	pos = [0 for i in range(len(a))]
	for i in range(n):
		pos[a[i] - 1] = i
	last = -1
	res = m
	for i in range(m):
		if pos[b[i] - 1] > last:
			res += 2 * (pos[b[i] - 1] - i)
			last = pos[b[i] - 1]
	print(res)


import sys
from sys import stdin, stdout
import bisect
import math
import heapq

def modinv(n, p):
	return pow(n, p - 2, p)

def cin():
	return map(int, sin().split())

def ain():
	return list(map(int, sin().split()))

def sin():
	return input()

def inin():
	return int(input())
import math

def Divisors(n):
	l = []
	for i in range(1, int(math.sqrt(n) + 1)):
		if n % i == 0:
			if n // i == i:
				l.append(i)
			else:
				l.append(i)
				l.append(n // i)
	return l

def main():
	t = inin()
	for _ in range(t):
		(n, m) = cin()
		a = ain()
		b = ain()
		d = {}
		j = 0
		ans = 0
		for i in range(m):
			if b[i] in d:
				ans += 1
				continue
			while j < n:
				d[a[j]] = 1
				if b[i] == a[j]:
					ans += 2 * (j - i) + 1
					break
				j += 1
		print(ans)
py2 = round(0.5)
if py2:
	from future_builtins import ascii, filter, hex, map, oct, zip
	range = xrange
import os, sys
from io import IOBase, BytesIO
BUFSIZE = 8192

class FastIO(BytesIO):
	newlines = 0

	def __init__(self, file):
		self._file = file
		self._fd = file.fileno()
		self.writable = 'x' in file.mode or 'w' in file.mode
		self.write = super(FastIO, self).write if self.writable else None

	def _fill(self):
		s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
		self.seek((self.tell(), self.seek(0, 2), super(FastIO, self).write(s))[0])
		return s

	def read(self):
		while self._fill():
			pass
		return super(FastIO, self).read()

	def readline(self):
		while self.newlines == 0:
			s = self._fill()
			self.newlines = s.count(b'\n') + (not s)
		self.newlines -= 1
		return super(FastIO, self).readline()

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

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		if py2:
			self.write = self.buffer.write
			self.read = self.buffer.read
			self.readline = self.buffer.readline
		else:
			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))
input = lambda : sys.stdin.readline().rstrip('\r\n')
import sys

class ostream:

	def __lshift__(self, a):
		sys.stdout.write(str(a))
		return self
cout = ostream()
endl = '\n'

def readnumbers(zero=0):
	conv = ord if py2 else lambda x: x
	A = []
	numb = zero
	sign = 1
	i = 0
	s = sys.stdin.buffer.read()
	try:
		while True:
			if s[i] >= b'0'[0]:
				numb = 10 * numb + conv(s[i]) - 48
			elif s[i] == b'-'[0]:
				sign = -1
			elif s[i] != b'\r'[0]:
				A.append(sign * numb)
				numb = zero
				sign = 1
			i += 1
	except:
		pass
	if s and s[-1] >= b'0'[0]:
		A.append(sign * numb)
	return A
main()


t = int(input())
for _ in range(t):
	narr = [-1] * 100001
	marr = [-1] * 100001
	(n, m) = map(int, input().split(' '))
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	k = 0
	for i in a:
		narr[i] = k
		k += 1
	k = 0
	for i in b:
		marr[i] = k
		k += 1
	s = 2 * narr[b[0]] + 1
	i = 1
	s1 = narr[b[0]]
	count = 1
	while i < m:
		if narr[b[i]] < s1:
			s += 1
		else:
			s1 = narr[b[i]]
			s += 2 * (narr[b[i]] - count) + 1
		count += 1
		i += 1
	print(s)


def input_ints():
	return [int(_) for _ in input().split()]
T = int(input())
for cc in range(T):
	(n, m) = input_ints()
	a = input_ints()
	b = input_ints()
	pos_of = {a[i]: i for i in range(n)}
	good = set()
	ra = a[::-1]
	ans = 0
	for (cnt, i) in enumerate(b):
		if i in good:
			ans += 1
		else:
			while ra[-1] != i:
				good.add(ra[-1])
				ra.pop()
			ra.pop()
			ans += 1 + 2 * (pos_of[i] - cnt)
	print(ans)


import sys

def get_ints():
	return list(map(int, sys.stdin.readline().strip().split()))
testcases = int(input())
for testcase in range(testcases):
	temparr = get_ints()
	n = temparr[0]
	m = temparr[1]
	arra = get_ints()
	arrb = get_ints()
	dicts = {}
	ans = 0
	arraindex = 0
	for getelem in arrb:
		if getelem in dicts:
			ans += 1
			dicts[getelem] -= 1
			if dicts[getelem] == 0:
				del dicts[getelem]
			continue
		ii = 0
		for i in range(arraindex, n):
			ii += 1
			if arra[i] != getelem:
				dicts[arra[i]] = 1
			else:
				break
		arraindex += ii
		getlen = len(dicts)
		ans += getlen * 2
		ans += 1
	print(ans)


import os
import sys
from io import BytesIO, IOBase
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))
input = lambda : sys.stdin.readline().rstrip('\r\n')

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

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

def N():
	return int(input())

def comb(n, m):
	return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0

def perm(n, m):
	return factorial(n) // factorial(n - m) if n >= m else 0

def mdis(x1, y1, x2, y2):
	return abs(x1 - x2) + abs(y1 - y2)

def toord(c):
	return ord(c) - ord('a')

def lcm(a, b):
	return a * b // lcm(a, b)
mod = 998244353
INF = float('inf')
from math import factorial, sqrt, ceil, floor, gcd
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush

def main():
	for _ in range(N()):
		(n, m) = RL()
		arra = RLL()
		arrb = RLL()
		rec = [0] * (n + 1)
		for i in range(n):
			rec[arra[i]] = i
		ma = -1
		res = 0
		for i in range(m):
			now = rec[arrb[i]]
			if now <= ma:
				res += 1
			else:
				res += (now - i) * 2 + 1
				ma = max(ma, now)
		print(res)
main()


t = int(input())
for p in range(t):
	(n, m) = map(int, input().split())
	stack = list(map(int, input().split()))
	send = list(map(int, input().split()))
	depth = [0] * (n + 1)
	for i in range(n):
		depth[stack[i]] = i
	ans = 0
	max_dep = -1
	for i in range(m):
		gift = send[i]
		if depth[gift] > max_dep:
			max_dep = depth[gift]
			ans += (max_dep - i) * 2 + 1
		else:
			ans += 1
	print(ans)


t = int(input())
while t > 0:
	(n, m) = [int(x) for x in input().split()]
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	map1 = dict()
	i = 0
	while i < len(a):
		map1[str(a[i])] = i
		i += 1
	check = set()
	j = 0
	sum = 0
	for present in b:
		if present not in check:
			sum = sum + 2 * (map1[str(present)] - j) + 1
			i = map1[str(present)] - 1
			while i >= 0 and (not a[i] in check):
				check.add(a[i])
				i -= 1
			j += 1
		else:
			check.remove(present)
			sum += 1
			j += 1
	print(sum)
	t -= 1


import os
import sys
from io import BytesIO, IOBase
from collections import Counter, defaultdict
from collections import deque
from functools import cmp_to_key
import math

def sin():
	return input()

def ain():
	return list(map(int, sin().split()))

def sain():
	return input().split()

def iin():
	return int(sin())
MAX = float('inf')
MIN = float('-inf')
MOD = 1000000007

def sieve(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
	s = set()
	for p in range(2, n + 1):
		if prime[p]:
			s.add(p)
	return s

def readTree(n, m):
	adj = [deque([]) for _ in range(n + 1)]
	for _ in range(m):
		(u, v) = ain()
		adj[u].append(v)
		adj[v].append(u)
	return adj

def solve(c1, c2, maxi1, maxi2):
	for i in range(1, maxi1 + 1):
		if i not in c1:
			return False
	for i in range(1, maxi2 + 1):
		if i not in c2:
			return False
	return True

def main():
	for _ in range(iin()):
		(n, m) = ain()
		a = ain()
		b = ain()
		idx = {}
		for i in range(n):
			idx[a[i]] = i + 1
		maxi = -1
		ans = 0
		size = n
		for i in range(m):
			if maxi == -1:
				maxi = idx[b[i]]
				ans += (maxi - 1) * 2 + 1
				size -= 1
			elif idx[b[i]] < maxi:
				ans += 1
				size -= 1
			else:
				maxi = idx[b[i]]
				ans += (maxi - 1 - (n - size)) * 2 + 1
				size -= 1
		print(ans)
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')
if os.getcwd() == 'D:\\code':
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
	input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	l = list(map(int, input().split()))
	k = list(map(int, input().split()))
	d = {}
	for i in range(n):
		d[l[i]] = i
	t = -1
	f = 0
	ans = 0
	for i in k:
		if d[i] > t:
			t = d[i]
			ans += 2 * (t - f)
		f += 1
		ans += 1
	print(ans)


t = int(input())
while t > 0:
	t -= 1
	s = input()
	v = []
	v = s.split()
	n = int(v[0])
	k = int(v[1])
	s = input()
	v = []
	v = s.split()
	v = [0] + v[:]
	s = input()
	v2 = []
	v2 = s.split()
	v2 = [0] + v2[:]
	ap = [0] * 100003
	for i in range(1, n + 1):
		v[i] = int(v[i])
		ap[v[i]] = i
	mare = 0
	sol = 0
	for i in range(1, k + 1):
		v2[i] = int(v2[i])
		if ap[v2[i]] <= mare:
			sol += 1
			continue
		mare = max(mare, ap[v2[i]])
		sol += 2 * (ap[v2[i]] - i) + 1
	print(str(sol))


for _ in range(int(input())):
	(n, m) = list(map(int, input().split()))
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	pos = {}
	for (i, el) in enumerate(a):
		pos[el] = i
	lastId = pos[b[0]]
	time = 2 * lastId + 1
	for i in range(1, m):
		if lastId < pos[b[i]]:
			time += 2 * (pos[b[i]] - i) + 1
			lastId = pos[b[i]]
		else:
			time += 1
	print(time)


t = int(input())
for i in range(t):
	(n, m) = map(int, input().split())
	gifts = list(map(int, input().split()))
	arr = list(map(int, input().split()))
	gifts_set = set()
	ans = 0
	k = 0
	for j in range(m):
		if arr[j] not in gifts_set:
			while gifts[k] != arr[j]:
				if gifts[k] != arr[j]:
					gifts_set.add(gifts[k])
					k += 1
			ans += 2 * len(gifts_set) + 1
			temp = set()
			temp.add(arr[j])
			gifts_set -= temp
			k += 1
		else:
			temp = set()
			temp.add(arr[j])
			gifts_set -= temp
			ans += 1
	print(ans)


from sys import stdin, stdout
t = int(stdin.readline().strip())
for _ in range(t):
	(n, m) = map(int, stdin.readline().split())
	presents = list(map(int, stdin.readline().split()))
	orders = list(map(int, stdin.readline().split()))
	(ip, io, pstart) = (0, 0, 0)
	found = set()
	oset = set(orders)
	time = 0
	unstkcount = 0
	o = orders[io]
	while io < len(orders):
		ip = presents.index(o, pstart)
		isect = oset.intersection(presents[pstart:ip])
		unstkcount += ip - pstart
		time += 2 * unstkcount + 1
		pstart = ip + 1
		found.update(isect)
		io += 1
		while io < len(orders):
			o = orders[io]
			if o in found:
				time += 1
				unstkcount -= 1
			else:
				break
			io += 1
	stdout.write('{}\n'.format(time))