Ayush is a cashier at the shopping center. Recently his department has started a ''click and collect" service which allows users to shop online. 

The store contains k items. n customers have already used the above service. Each user paid for m items. Let a_{ij} denote the j-th item in the i-th person's order.

Due to the space limitations all the items are arranged in one single row. When Ayush receives the i-th order he will find one by one all the items a_{ij} (1 ≤ j ≤ m) in the row. Let pos(x) denote the position of the item x in the row at the moment of its collection. Then Ayush takes time equal to pos(a_{i}1) + pos(a_{i}2) + ... + pos(a_{im}) for the i-th customer.

When Ayush accesses the x-th element he keeps a new stock in the front of the row and takes away the x-th element. Thus the values are updating.

Your task is to calculate the total time it takes for Ayush to process all the orders.

You can assume that the market has endless stock.


-----Input-----

The first line contains three integers n, m and k (1 ≤ n, k ≤ 100, 1 ≤ m ≤ k) — the number of users, the number of items each user wants to buy and the total number of items at the market.

The next line contains k distinct integers p_{l} (1 ≤ p_{l} ≤ k) denoting the initial positions of the items in the store. The items are numbered with integers from 1 to k.

Each of the next n lines contains m distinct integers a_{ij} (1 ≤ a_{ij} ≤ k) — the order of the i-th person.


-----Output-----

Print the only integer t — the total time needed for Ayush to process all the orders.


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

Output
14



-----Note-----

Customer 1 wants the items 1 and 5.

pos(1) = 3, so the new positions are: [1, 3, 4, 2, 5].

pos(5) = 5, so the new positions are: [5, 1, 3, 4, 2].

Time taken for the first customer is 3 + 5 = 8.

Customer 2 wants the items 3 and 1.

pos(3) = 3, so the new positions are: [3, 5, 1, 4, 2].

pos(1) = 3, so the new positions are: [1, 3, 5, 4, 2].

Time taken for the second customer is 3 + 3 = 6.

Total time is 8 + 6 = 14.

Formally pos(x) is the index of x in the current row.

Difficulty: MEDIUM
Tags: Complete search
Skill types: Complete search

Starter code:

Solutions:
l1 = list(map(int, input().split()))
n = l1[0]
m = l1[1]
k = l1[2]
a = list(map(int, input().split()))
tot = 0
for i in range(n):
	orders = list(map(int, input().split()))
	for i in range(m):
		b = []
		val = orders[i]
		pos = a.index(val)
		tot = tot + pos + 1
		a.pop(pos)
		b.append(val)
		b = b + a
		a = b
print(tot)


import sys

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

def iinput():
	return int(input())

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

def listinput():
	return list(map(int, input().split()))
(n, m, k) = minput()
p = listinput()
answer = [0]
for i in range(n):
	item = listinput()
	time = 0
	for j in item:
		time += p.index(j) + 1
		p = [j] + p[:p.index(j)] + p[p.index(j) + 1:]
	answer.append(time + answer[i])
print(answer[-1])


ln = input().split(' ')
n = int(ln[0])
m = int(ln[1])
k = int(ln[2])
x = 0
pila = input().split(' ')
for i in range(n):
	cus = input().split(' ')
	for j in range(m):
		ind = pila.index(cus[j])
		x = x + ind + 1
		pila.insert(0, pila.pop(ind))
print(x)


(n, m, k) = map(int, input().split())
sum = 0
a = list(map(int, input().split()))
for p in range(n):
	x = list(map(int, input().split()))
	for i in range(m):
		for j in range(k):
			if x[i] == a[j]:
				sum += j + 1
				for u in range(j, 0, -1):
					a[u] = a[u - 1]
				a[0] = x[i]
				break
print(sum)


import sys
input = sys.stdin.readline
(n, m, k) = map(int, input().split())
a = list(map(int, input().split()))
res = 0
for i in range(n):
	for j in input().split():
		yy = int(j)
		res += a.index(yy) + 1
		a.remove(yy)
		a = [yy] + a
print(res)


[n, m, k] = [int(a) for a in input('').split(' ')]
pos = [int(a) for a in input('').split(' ')]
time = 0
for i in range(n):
	orders = []
	orders += [int(a) for a in input('').split(' ')]
	for o in orders:
		ind = pos.index(o)
		time += ind + 1
		pos = [pos.pop(ind)] + pos
print(time)


import sys
import math
import itertools as it
import operator as op
import fractions as fr
(n, m, k) = map(int, sys.stdin.readline().split())
P = list(map(int, sys.stdin.readline().split()))
P = P[::-1]
r = 0
for _ in range(n):
	Aj = map(int, sys.stdin.readline().split())
	for a in Aj:
		idx = P.index(a)
		r += k - idx
		del P[idx]
		P.append(a)
print(r)


(n, m, k) = map(int, input().split())
pos = list(map(int, input().split()))
d = 0
for i in range(n):
	for a in list(map(int, input().split())):
		for j in range(k):
			if pos[j] == a:
				del pos[j]
				pos = [a] + pos
				d += j + 1
print(d)


s = input().split()
n = int(s[0])
m = int(s[1])
k = int(s[2])
pos = 0
goods = [int(x) for x in input().split()]
for i in range(n):
	buy = input().split()
	for u in buy:
		x = int(u)
		pos = pos + goods.index(x) + 1
		goods.remove(x)
		goods.insert(0, x)
print(pos)


(n, m, k) = map(int, input().split())
P = list(map(int, input().split()))
L = [list(map(int, input().split())) for _ in range(n)]
r = 0
for i in range(n):
	for j in range(m):
		e = P.index(L[i][j])
		r += e + 1
		P = [L[i][j]] + P[:e] + P[e + 1:]
print(r)


(n, m, k) = map(int, input().split())
goods = list(map(int, input().split()))
total_time = 0
for i in range(n):
	goods_i = list(map(int, input().split()))
	for j in range(m):
		pos = goods.index(goods_i[j])
		total_time += pos + 1
		goods.remove(goods_i[j])
		goods = [goods_i[j]] + goods
print(total_time)


[n, k, m] = [int(x) for x in input().split()]
u = []
result = 0
for i in range(1):
	t = [int(x) for x in input().split()]
for i in range(1, n + 1):
	x = [int(x) for x in input().split()]
	for j in range(k):
		u.append(x[j])
for l in range(n * k):
	a = u[l]
	b = t.index(a) + 1
	result = result + b
	t.remove(a)
	t.insert(0, a)
print(result)


def main():
	(n, m, k) = list(map(int, input().split()))
	(aa, t) = (list(map(int, input().split())), n * m * k)
	aa.reverse()
	(u, v, w) = (aa.index, aa.remove, aa.append)
	for _ in range(n):
		for a in map(int, input().split()):
			t -= u(a)
			v(a)
			w(a)
	print(t)

def __starting_point():
	main()
__starting_point()


(n, m, k) = map(int, input().split())
(p, v) = (input().split(), 0)
for i in range(n):
	for x in input().split():
		c = p.index(x)
		v += c + 1
		p.pop(c)
		p.insert(0, x)
print(v)


from sys import stdin as fin

class node:

	def __init__(self, val=None):
		self.prev = self.next = None
		self.val = val

	@staticmethod
	def link(node1, node2):
		node1.next = node2
		node2.prev = node1
		return node2

	@staticmethod
	def move(node1, node2, inode1, inode2):
		if inode1.prev is not None:
			inode1.prev.next = inode2.next
		if inode2.next is not None:
			inode2.next.prev = inode1.prev
		node1 = node.link(node1, inode1)
		node2 = node.link(inode2, node2)
		return (node1, node2)
(n, m, k) = map(int, fin.readline().split())
arr = list(map(int, fin.readline().split()))
cur = line = node()
for num in arr:
	cur = node.link(cur, node(num))
res = 0
for i in range(n):
	buy = list(map(int, fin.readline().split()))
	for num in buy:
		cur = line
		cnt = 0
		while cur.val != num:
			cur = cur.next
			cnt += 1
		res += cnt
		if line.next != cur:
			line = node.move(line, line.next, cur, cur)[0].prev
print(res)


(n, m, k) = map(int, input().split())
l = list(map(int, input().split()))
cusOrders = []
for i in range(n):
	cusOrders = cusOrders + list(map(int, input().split()))
totTime = 0
sizeOfList = len(l)
for x in cusOrders:
	pos = l.index(x)
	totTime = totTime + pos + 1
	n = [x] + l[:pos]
	if pos != sizeOfList - 1:
		n = n + l[pos + 1:]
	l = n
print(totTime)


(n, m, k) = map(int, input().split())
arr = list(map(int, input().split()))
ans = 0
for i in range(n):
	for j in map(int, input().split()):
		x = arr.index(j)
		ans += x + 1
		arr.pop(x)
		arr = [j] + arr[:]
print(ans)


(n, m, k) = map(int, input().split())
p = list(map(int, input().split()))
len_a = n * m
a = [None] * len_a
for i in range(n):
	cur_line = list(map(int, input().split()))
	for j in range(m):
		a[i * m + j] = cur_line[j]
sum = 0
for i in range(len_a - 1):
	index_cur = p.index(a[i])
	sum += index_cur + 1
	for j in range(index_cur):
		(p[index_cur - j], p[index_cur - j - 1]) = (p[index_cur - j - 1], p[index_cur - j])
sum += p.index(a[-1]) + 1
print(sum)


(user, item, total) = list(map(int, input().split()))
items = list(map(int, input().split()))
to = 0
for i in range(user):
	a = list(map(int, input().split()))
	for j in a:
		to += items.index(j) + 1
		items.pop(items.index(j))
		items = [j] + items
print(to)


def get_index(el, lst):
	for (idx, element) in enumerate(lst):
		if element == el:
			return idx
	return -1
(n, m, k) = (int(cur_num) for cur_num in input().split())
things = [int(cur_num) for cur_num in input().split()]
ans = 0
for _ in range(n):
	bought = [int(cur_num) for cur_num in input().split()]
	for purchase in bought:
		idx = get_index(purchase, things)
		ans += idx + 1
		del things[idx]
		things = [purchase] + things
print(ans)


(n, m, k) = map(int, input().split())
b = [0] * (k + 1)
a = list(map(int, input().split()))
for i in range(k):
	b[a[i]] = i + 1
s = 0
for i in range(n):
	c = list(map(int, input().split()))
	for j in range(m):
		s += b[c[j]]
		for l in range(b[c[j]] - 1, 0, -1):
			b[a[l - 1]] += 1
			a[l] = a[l - 1]
		b[c[j]] = 1
		a[0] = c[j]
print(s)


(n, m, k) = map(int, input().split())
v = list(map(int, input().split()))
place = 0
s = 0
for l in range(n):
	a = list(map(int, input().split()))
	for i in a:
		for j in range(k):
			if v[j] == i:
				place = j
				break
		s += place + 1
		while place > 0:
			v[place] = v[place - 1]
			place -= 1
		v[0] = i
print(s)


(n, m, k) = map(int, input().split())
a = list(map(int, input().split()))
time = 0
for i in range(n):
	c = list(map(int, input().split()))
	for j in c:
		for k in range(len(a)):
			if a[k] == j:
				p = k
				break
		time += p + 1
		a = [j] + a[:k] + a[k + 1:]
print(time)


from collections import *
(n, m, k) = map(int, input().split())
p = list(map(int, input().split()))
sn = 0
for _ in range(n):
	r = list(map(int, input().split()))
	for j in r:
		i = p.index(j)
		sn += i + 1
		p.pop(i)
		p = [j] + p
print(sn)


(n, m, k) = map(int, input().split())
A = list(map(int, input().split()))
time = 0
for a in range(n):
	B = list(map(int, input().split()))
	for i in B:
		K = [i]
		time += A.index(i) + 1
		for a in A:
			if a != i:
				K.append(a)
		A = K
print(time)


number = int(input().split()[0])
array = input().split()
sum = 0
for i in range(0, number):
	items = input().split()
	for j in items:
		buffer = []
		sum = sum + int(array.index(j)) + 1
		buffer.append(j)
		array.remove(j)
		array = buffer + array
print(sum)


f = lambda : map(int, input().split())
(n, m, k) = f()
a = list(f())
s = m * n
for i in range(n):
	for b in f():
		i = a.index(b)
		s += i
		a = [a.pop(i)] + a
print(s)


from __future__ import division, print_function
import os
import 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

class ListNode:

	def __init__(self, idx, nxt=None):
		self.idx = idx
		self.nxt = nxt

def solve():
	(n, m, k) = invr()
	head = ListNode(-1)
	lst = inlt()
	cur = head
	for el in lst:
		cur.nxt = ListNode(el)
		cur = cur.nxt
	res = 0
	for i in range(n):
		purchases = inlt()
		for el in purchases:
			prev = head
			cur = head.nxt
			count = 1
			while el != cur.idx:
				prev = cur
				cur = cur.nxt
				count += 1
			prev.nxt = cur.nxt
			cur.nxt = head.nxt
			head.nxt = cur
			res += count
	print(res)

def main():
	t = 1
	for i in range(t):
		solve()
BUFSIZE = 8192

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

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

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

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

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


import logging
import copy
import sys
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
line = []

def solve(pos):
	global line
	s = 0
	for p in pos:
		idx = line.index(p)
		s += idx + 1
		del line[idx]
		line = [p] + line
	return s

def main():
	global line
	firstLine = input().split()
	firstLine = list(map(int, firstLine))
	line = input().split()
	line = list(map(int, line))
	s = 0
	for i in range(firstLine[0]):
		n = input().split()
		n = list(map(int, n))
		s += solve(n)
	print(s)

def log(*message):
	logging.debug(message)
main()


import sys
import math
data = sys.stdin.read().split()
data_ptr = 0

def data_next():
	global data_ptr, data
	data_ptr += 1
	return data[data_ptr - 1]
N = int(data_next())
M = int(data_next())
K = int(data_next())
arr = []
for i in range(K):
	arr.append(int(data_next()))
ans = 0
for i in range(N):
	for j in range(M):
		item = int(data_next())
		idx = arr.index(item)
		arr = [item] + arr[0:idx] + arr[idx + 1:]
		ans += idx + 1
print(ans)


import io, sys, atexit, os
import math as ma
from sys import exit
from decimal import Decimal as dec
from itertools import permutations
from itertools import combinations

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

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

def nu():
	return int(input())

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

def lcm(x, y):
	gg = find_gcd(x, y)
	return x * y // gg

def printDivisors(n):
	i = 1
	cc = 0
	while i <= ma.sqrt(n):
		if n % i == 0:
			if n / i == i:
				cc += 1
			else:
				cc += 2
		i = i + 1
	return cc
mm = 1000000007
yp = 0

def solve():
	t = 1
	for tt in range(t):
		(n, m, k) = num()
		a = li()
		ff = a
		ss = 0
		for i in range(n):
			b = li()
			for j in range(m):
				for ll in range(k):
					if b[j] == ff[ll]:
						ss += ll + 1
						ff = [b[j]] + ff[0:ll] + ff[ll + 1:]
						break
		print(ss)
solve()


(n, m, k) = map(int, input().split())
p = list(map(int, input().split()))
a = [list(map(int, input().split())) for i in range(n)]
st = 0
for i in range(n):
	for j in range(m):
		for g in range(k):
			if a[i][j] == p[g]:
				p.insert(0, p[g])
				del p[g + 1]
				st += g + 1
				g -= 1
print(st)


s = input().split(' ')
goods_count = int(s[0])
goods = input().split(' ')
t = 0
for i in range(goods_count):
	s = input().split(' ')
	for item in s:
		t += goods.index(item) + 1
		del goods[goods.index(item)]
		goods.insert(0, item)
print(t)


(n, m, k) = [int(x) for x in input().split()]
ls = [str(x) for x in input().split()]
dct = dict(enumerate(ls, start=1))
dct = dict(((v, k) for (k, v) in dct.items()))
S = 0
for i in range(n):
	a_list = [str(x) for x in input().split()]
	for a in a_list:
		pos = dct[a]
		S += pos
		ls.remove(a)
		ls = [a] + ls
		dct = dict(enumerate(ls, start=1))
		dct = dict(((v, k) for (k, v) in dct.items()))
print(S)


(n, m, k) = map(int, input().split())
k = list(map(int, input().split()))
a = []
c = 0
for i in range(n):
	n = list(map(int, input().split()))
	a.append(n)
for i in a:
	for j in i:
		c += k.index(j) + 1
		k.remove(j)
		k = [j] + k
print(c)


I = lambda : map(int, input().split())
(n, m, k) = I()
a = list(I())
(l, s) = ([0] * (k + 1), 0)
for i in range(k):
	l[a[i]] = i
for i in range(n):
	b = list(I())
	for j in b:
		v = l[j]
		s += v + 1
		for g in range(1, k + 1):
			l[g] += l[g] < v
		l[j] = 0
print(s)


(n, m, k) = list(map(int, input().strip().split()))
a = list(map(int, input().strip().split()))
d = dict()
for i in range(k):
	d[a[i]] = i + 1
c = 0
for i in range(n):
	b = list(map(int, input().strip().split()))
	for el in b:
		e = d[el]
		for elk in d.keys():
			if d[elk] > e:
				pass
			elif d[elk] == e:
				d[elk] = 1
			else:
				d[elk] += 1
		c += e
print(c)


(n, m, k) = map(int, input().split())
a = list(map(int, input().split()))
sums = 0
for i in range(n):
	p = list(map(int, input().split()))
	for j in range(m):
		sums += a.index(p[j]) + 1
		a.remove(p[j])
		a.insert(0, p[j])
print(sums)


(n, m, k) = list(map(int, input().split()))
p = list(map(int, input().split()))
p.reverse()
ans = 0
for i in range(n):
	z = list(map(int, input().split()))
	for j in z:
		v = 0
		for k in range(len(p) - 1, -1, -1):
			v += 1
			if p[k] == j:
				ans += v
				p.pop(k)
				p.append(j)
				break
print(ans)


from sys import stdin, stdout
from collections import deque
(numbers, everyq, allq) = map(int, stdin.readline().split())
items = deque(list(map(int, stdin.readline().split())))
cnt = 0
for i in range(numbers):
	current = map(int, stdin.readline().split())
	for n in current:
		ind = 0
		while items[ind] != n:
			ind += 1
		cnt += ind + 1
		value = items[ind]
		for j in range(ind, 0, -1):
			items[j] = items[j - 1]
		items[0] = value
stdout.write(str(cnt))


def main():
	(n, m, k) = map(int, input().split())
	(aa, t) = (list(map(int, input().split())), n * m * k)
	aa.reverse()
	for _ in range(n):
		for a in map(int, input().split()):
			i = aa.index(a)
			t -= i
			del aa[i]
			aa.append(a)
	print(t)
main()


(n, m, k) = map(int, input().split())
p = list(map(int, input().split()))
t = 0
for i in range(n):
	a = list(map(int, input().split()))
	for x in a:
		ind = p.index(x)
		t += ind + 1
		p.pop(ind)
		p.insert(0, x)
print(t)


import sys
import bisect
from bisect import bisect_left as lb
input_ = lambda : sys.stdin.readline().strip('\r\n')
from math import log
from math import gcd
from math import atan2, acos
from random import randint
sa = lambda : input_()
sb = lambda : int(input_())
sc = lambda : input_().split()
sd = lambda : list(map(int, input_().split()))
se = lambda : float(input_())
sf = lambda : list(input_())
flsh = lambda : sys.stdout.flush()
mod = 10 ** 9 + 7
gp = []
cost = []
dp = []
mx = []
ans1 = []
ans2 = []
special = []
specnode = []
a = 0
kthpar = []

def dfs(root, par):
	if par != -1:
		dp[root] = dp[par] + 1
	for i in range(1, 20):
		if kthpar[root][i - 1] != -1:
			kthpar[root][i] = kthpar[kthpar[root][i - 1]][i - 1]
	for child in gp[root]:
		if child == par:
			continue
		kthpar[child][0] = root
		dfs(child, root)

def hnbhai():
	(n, m, k) = sd()
	pos = sd()
	tot = 0
	for i in range(n):
		temp = sd()
		for j in temp:
			tot += pos.index(j) + 1
			pos.pop(pos.index(j))
			pos.insert(0, j)
	print(tot)
for _ in range(1):
	hnbhai()


(n, m, k) = list(map(lambda q: int(q), input().split()))
k_lst = list(map(lambda q: int(q), input().split()))
order_lst = []
for i in range(n):
	lst = list(map(lambda q: int(q), input().split()))
	order_lst += lst

def calcCost(n, m, k, k_lst):
	total_min = 0
	_index = 0
	for i in range(n * m):
		_item = order_lst[_index]
		for (index, item) in enumerate(k_lst):
			if item == _item:
				total_min += index + 1
				break
		k_lst = [k_lst[index]] + k_lst[0:index] + k_lst[index + 1:]
		_index += 1
	return total_min
print(calcCost(n, m, k, k_lst))


(n, m, k) = list(map(int, input().split()))
l = list(map(int, input().split()))
t = 0
for i in range(n):
	for item in map(int, input().split()):
		t += l.index(item) + 1
		l.remove(item)
		l.insert(0, item)
print(t)


(n, m, k) = map(int, input().split())
p = [int(x) for x in input().split()]
inds = [-1 for i in range(k + 1)]
for i in range(k):
	inds[p[i]] = i
res = 0
for i in range(n):
	a = [int(x) for x in input().split()]
	for aij in a:
		pos = inds[aij]
		res += pos + 1
		while pos > 0:
			inds[p[pos - 1]] += 1
			p[pos] = p[pos - 1]
			pos -= 1
		p[0] = aij
		inds[aij] = 0
print(res)


(n, m, k) = map(int, input().split())
a = list(map(int, input().split()))
ans = 0
for i in range(n):
	orders = map(int, input().split())
	for order in orders:
		ans += a.index(order) + 1
		a.remove(order)
		a.insert(0, order)
print(ans)


import math
[n, m, k] = map(int, input().split(' '))
queue = list(map(int, input().split(' ')))
time = 0
for i in range(n):
	items = list(map(int, input().split(' ')))
	for j in range(m):
		item = items[j]
		time += queue.index(item) + 1
		queue.remove(item)
		queue.insert(0, item)
print(time)


(n, m, k) = map(int, input().split(' '))
p = input().split(' ')
ans = 0
for _ in range(0, n):
	il = input().split(' ')
	for i in il:
		idx = p.index(i)
		ans += idx + 1
		del p[idx]
		p = [i] + p
print(ans)


(n, m, k) = map(int, input().split())
c = list(map(int, input().split()))
r = 0
for _ in range(n):
	for x in map(int, input().split()):
		i = c.index(x)
		r += i + 1
		c.pop(i)
		c.insert(0, x)
print(r)


(n, m, k) = map(int, input().split())
queue = list(map(int, input().split()))
mass = []
for i in range(n):
	mass += list(map(int, input().split()))
count = 0
for elem in mass:
	c = queue.index(elem)
	count += c + 1
	queue.pop(c)
	queue.insert(0, elem)
print(count)


(n, m, k) = map(int, input().split())
ps = list(map(int, input().split()))
xs = []
for _ in range(n):
	xs.append(list(map(int, input().split())))

def get(x):
	i = ps.index(x)
	ps[1:i + 1] = ps[0:i]
	ps[0] = x
	return i + 1
print(sum(map(lambda ys: sum(map(get, ys)), xs)))


(n, m, k) = [int(x) for x in input().split()]
a = [None] * k
initial = [int(x) for x in input().split()]
time = 0
for c in range(n):
	for obj in input().split():
		obj = int(obj)
		pos = initial.index(obj)
		time += pos + 1
		del initial[pos]
		initial.insert(0, obj)
print(time)


tmp = input().split(' ')
n = int(tmp[0])
m = int(tmp[1])
k = int(tmp[2])
tmp = input().split(' ')
pos = []
need = []
for i in range(k):
	pos.append(int(tmp[i]))
time = 0
for i in range(n):
	tmp = input().split(' ')
	need.clear()
	for j in range(m):
		need.append(int(tmp[j]))
	for j in range(m):
		curpos = pos.index(need[j])
		time = time + curpos + 1
		del pos[curpos]
		pos.insert(0, need[j])
print(time)


import sys
from bisect import bisect_right as rb
from collections import deque
from queue import PriorityQueue
from math import *
input_ = lambda : sys.stdin.readline().strip('\r\n')
ii = lambda : int(input_())
il = lambda : list(map(int, input_().split()))
ilf = lambda : list(map(float, input_().split()))
ip = lambda : input_()
fi = lambda : float(input_())
ap = lambda ab, bc, cd: ab[bc].append(cd)
li = lambda : list(input_())
pr = lambda x: print(x)
prinT = lambda x: print(x)
f = lambda : sys.stdout.flush()
mod = 10 ** 9 + 7
(n, m, k) = il()
p = il()
ans = 0
for i in range(n):
	x = il()
	for j in x:
		ind = p.index(j)
		ans += ind + 1
		p.pop(ind)
		p.insert(0, j)
print(ans)


(n, m, k) = map(int, input().split())
p = list(map(int, input().split()))
moves = 0
for i in range(n):
	c = list(map(int, input().split()))
	for item in c:
		pos = 0
		while item != p[pos]:
			pos = pos + 1
		moves += pos + 1
		p = [p.pop(pos)] + p
print(moves)


import sys
(n, m, k) = map(int, input().split())
items = list(map(int, input().split()))
ans = 0
for _ in range(n):
	for x in map(int, input().split()):
		i = items.index(x)
		ans += i + 1
		items.insert(0, items.pop(i))
print(ans)


(n, m, k) = map(int, input().split())
q = list(map(int, input().split()))
ans = 0
for i in range(n):
	lst = list(map(int, input().split()))
	for j in lst:
		ind = q.index(j)
		ans += ind + 1
		q.pop(ind)
		q.insert(0, j)
print(ans)


(n, m, k) = map(int, input().split())
pos = list(map(int, input().split()))
a = [list(map(int, input().split())) for i in range(n)]
ans = 0
for i in a:
	for j in i:
		ind = pos.index(j)
		ans += ind + 1
		pos.pop(ind)
		pos = [j] + pos
print(ans)


(n, m, k) = map(int, input().split())
order = list(map(int, input().split()))
items = []
for i in range(n):
	items.append(list(map(int, input().split())))
ans = 0
for i in range(n):
	for j in range(m):
		item = order.index(items[i][j])
		ans += item + 1
		order.insert(0, order.pop(item))
print(ans)


[n, m, k] = [int(i) for i in input().split()]
a = [0] * (k + 1)
temp = [int(i) for i in input().split()]
for i in range(0, k):
	a[temp[i]] = i + 1
answer = 0
for z in range(0, n):
	temp = [int(i) for i in input().split()]
	for i in temp:
		answer += a[i]
		for l in range(1, k + 1):
			if a[l] < a[i]:
				a[l] += 1
		a[i] = 1
print(answer)


a = list(map(int, input().split()))
n = a[0]
m = a[1]
k = a[2]
b = list(map(int, input().split()))
t = 0
for i in range(n):
	arr = list(map(int, input().split()))
	for j in range(m):
		l = b.index(arr[j])
		t += 1 + l
		for h in range(l, 0, -1):
			b[h] = b[h - 1]
		b[0] = arr[j]
print(t)


(n, m, k) = map(int, input().split())
p = list(map(int, input().split()))
r = 0
for i in range(0, n):
	a = list(map(int, input().split()))
	for j in range(0, len(a)):
		index = p.index(a[j])
		r += index + 1
		p.insert(0, p.pop(index))
print(r)


(n, m, k) = map(int, input().split())
row = list(map(int, input().split()))
a = []
for _ in range(n):
	a += list(map(int, input().split()))
time = 0
for e in a:
	tmp = row.index(e)
	time += tmp + 1
	row.insert(0, row.pop(tmp))
print(time)


(n, m, k) = map(int, input().split())
P = list(map(int, input().split()))
count = 0
for i in range(n):
	X = list(map(int, input().split()))
	for j in X:
		t = P.index(j)
		count += t + 1
		P = [j] + P[:t] + P[t + 1:]
print(count)


from functools import cmp_to_key
from collections import deque, Counter
from heapq import heappush, heappop
from math import log, ceil
import sys
import os
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')
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))

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

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

def ii():
	return int(inp())

def si():
	return str(inp())

def li(lag=0):
	l = list(map(int, inp().split()))
	if lag != 0:
		for i in range(len(l)):
			l[i] += lag
	return l

def mi(lag=0):
	matrix = list()
	for i in range(n):
		matrix.append(li(lag))
	return matrix

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

def print_list(lista, space=' '):
	print(space.join(map(str, lista)))

def bisect_left(a, x):
	left = 0
	right = len(a)
	while left < right:
		mid = (left + right) // 2
		if a[mid] < x:
			left = mid + 1
		else:
			right = mid
	return left

def bisect_right(a, x):
	left = 0
	right = len(a)
	while left < right:
		mid = (left + right) // 2
		if a[mid] > x:
			right = mid
		else:
			left = mid + 1
	return left

def bisect_elements(a, x):
	return bisect_right(a, x) - bisect_left(a, x)
MOD = 10 ** 9 + 7
maxN = 5
FACT = [0] * maxN
INV_FACT = [0] * maxN

def add(x, y):
	return (x + y) % MOD

def multiply(x, y):
	return x * y % MOD

def power(x, y):
	if y == 0:
		return 1
	elif y % 2:
		return multiply(x, power(x, y - 1))
	else:
		a = power(x, y // 2)
		return multiply(a, a)

def inverse(x):
	return power(x, MOD - 2)

def divide(x, y):
	return multiply(x, inverse(y))

def allFactorials():
	FACT[0] = 1
	for i in range(1, maxN):
		FACT[i] = multiply(i, FACT[i - 1])

def inverseFactorials():
	n = len(INV_FACT)
	INV_FACT[n - 1] = inverse(FACT[n - 1])
	for i in range(n - 2, -1, -1):
		INV_FACT[i] = multiply(INV_FACT[i + 1], i + 1)

def coeffBinom(n, k):
	if n < k:
		return 0
	return multiply(FACT[n], multiply(INV_FACT[k], INV_FACT[n - k]))

def create_graph(n, m, undirected=1, unweighted=1):
	graph = [[] for i in range(n)]
	if unweighted:
		for i in range(m):
			[x, y] = li(lag=-1)
			graph[x].append(y)
			if undirected:
				graph[y].append(x)
	else:
		for i in range(m):
			[x, y, w] = li(lag=-1)
			w += 1
			graph[x].append([y, w])
			if undirected:
				graph[y].append([x, w])
	return graph

def create_tree(n, unweighted=1):
	children = [[] for i in range(n)]
	if unweighted:
		for i in range(n - 1):
			[x, y] = li(lag=-1)
			children[x].append(y)
			children[y].append(x)
	else:
		for i in range(n - 1):
			[x, y, w] = li(lag=-1)
			w += 1
			children[x].append([y, w])
			children[y].append([x, w])
	return children

def dist(tree, n, A, B=-1):
	s = [[A, 0]]
	(massimo, massimo_nodo) = (0, 0)
	distanza = -1
	v = [-1] * n
	while s:
		(el, dis) = s.pop()
		if dis > massimo:
			massimo = dis
			massimo_nodo = el
		if el == B:
			distanza = dis
		for child in tree[el]:
			if v[child] == -1:
				v[child] = 1
				s.append([child, dis + 1])
	return (massimo, massimo_nodo, distanza)

def diameter(tree):
	(_, foglia, _) = dist(tree, n, 0)
	(diam, _, _) = dist(tree, n, foglia)
	return diam

def dfs(graph, n, A):
	v = [-1] * n
	s = [[A, 0]]
	v[A] = 0
	while s:
		(el, dis) = s.pop()
		for child in graph[el]:
			if v[child] == -1:
				v[child] = dis + 1
				s.append([child, dis + 1])
	return v

def bfs(graph, n, A):
	v = [-1] * n
	s = deque()
	s.append([A, 0])
	v[A] = 0
	while s:
		(el, dis) = s.popleft()
		for child in graph[el]:
			if v[child] == -1:
				v[child] = dis + 1
				s.append([child, dis + 1])
	return v

def parents_children_root_unrooted_tree(tree, n, root=0):
	q = deque()
	visited = [0] * n
	parent = [-1] * n
	children = [[] for i in range(n)]
	q.append(root)
	while q:
		all_done = 1
		visited[q[0]] = 1
		for child in tree[q[0]]:
			if not visited[child]:
				all_done = 0
				q.appendleft(child)
		if all_done:
			for child in tree[q[0]]:
				if parent[child] == -1:
					parent[q[0]] = child
					children[child].append(q[0])
			q.popleft()
	return (parent, children)

def all_longest_path_passing_from_node(parent, children, n):
	q = deque()
	visited = [len(children[i]) for i in range(n)]
	downwards = [[0, 0] for i in range(n)]
	upward = [1] * n
	longest_path = [1] * n
	for i in range(n):
		if not visited[i]:
			q.append(i)
			downwards[i] = [1, 0]
	while q:
		node = q.popleft()
		if parent[node] != -1:
			visited[parent[node]] -= 1
			if not visited[parent[node]]:
				q.append(parent[node])
		else:
			root = node
		for child in children[node]:
			downwards[node] = sorted([downwards[node][0], downwards[node][1], downwards[child][0] + 1], reverse=True)[0:2]
	s = [node]
	while s:
		node = s.pop()
		if parent[node] != -1:
			if downwards[parent[node]][0] == downwards[node][0] + 1:
				upward[node] = 1 + max(upward[parent[node]], downwards[parent[node]][1])
			else:
				upward[node] = 1 + max(upward[parent[node]], downwards[parent[node]][0])
		longest_path[node] = downwards[node][0] + downwards[node][1] + upward[node] - min([downwards[node][0], downwards[node][1], upward[node]]) - 1
		for child in children[node]:
			s.append(child)
	return longest_path
(n, m, k) = li()
s = li()
o = []
for c in range(n):
	t = li()
	for e in t:
		o.append(e)
cost = 0
for el in o:
	for (i, els) in enumerate(s):
		if els == el:
			cost += i + 1
			I = i
	s = [s[I]] + s[:I] + s[I + 1:]
print(cost)


(n, m, k) = map(int, input().split())
kk = [int(i) for i in input().split()]
ss = 0
for _ in range(0, n):
	lst = [int(i) for i in input().split()]
	for i in range(0, m):
		k = kk.index(lst[i])
		ss += k + 1
		kk = [lst[i]] + kk[:k] + kk[k + 1:]
print(ss)