New Year is coming, and Jaehyun decided to read many books during 2015, unlike this year. He has n books numbered by integers from 1 to n. The weight of the i-th (1 ≤ i ≤ n) book is w_{i}.

As Jaehyun's house is not large enough to have a bookshelf, he keeps the n books by stacking them vertically. When he wants to read a certain book x, he follows the steps described below.  He lifts all the books above book x.  He pushes book x out of the stack.  He puts down the lifted books without changing their order.  After reading book x, he puts book x on the top of the stack. 

[Image] 

He decided to read books for m days. In the j-th (1 ≤ j ≤ m) day, he will read the book that is numbered with integer b_{j} (1 ≤ b_{j} ≤ n). To read the book, he has to use the process described in the paragraph above. It is possible that he decides to re-read the same book several times.

After making this plan, he realized that the total weight of books he should lift during m days would be too heavy. So, he decided to change the order of the stacked books before the New Year comes, and minimize the total weight. You may assume that books can be stacked in any possible order. Note that book that he is going to read on certain step isn't considered as lifted on that step. Can you help him?


-----Input-----

The first line contains two space-separated integers n (2 ≤ n ≤ 500) and m (1 ≤ m ≤ 1000) — the number of books, and the number of days for which Jaehyun would read books.

The second line contains n space-separated integers w_1, w_2, ..., w_{n} (1 ≤ w_{i} ≤ 100) — the weight of each book.

The third line contains m space separated integers b_1, b_2, ..., b_{m} (1 ≤ b_{j} ≤ n) — the order of books that he would read. Note that he can read the same book more than once.


-----Output-----

Print the minimum total weight of books he should lift, which can be achieved by rearranging the order of stacked books.


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

Output
12



-----Note-----

Here's a picture depicting the example. Each vertical column presents the stacked books. [Image]

Difficulty: MEDIUM_HARD
Tags: Mathematics

Greedy algorithms

Implementation

Constructive algorithms
Skill types: Greedy algorithms

Starter code:

Solutions:
(a, b) = map(int, input().split(' '))
c = list(map(int, input().split(' ')))
d = list(map(int, input().split(' ')))
e = []
dictx = {}
for i in range(1, a + 1):
	dictx[i] = c[i - 1]
for i in d:
	if i not in e:
		e.append(i)
tot = 0
for i in d:
	indx = e.index(i)
	tot += sum([dictx[i] for i in e[:indx]])
	e = [e[indx]] + e[:indx] + e[indx + 1:]
print(tot)


import sys

def main():
	(n, m) = tuple([int(x) for x in input().split()])
	w = [int(x) for x in input().split()]
	b = [int(x) - 1 for x in input().split()]
	o = []
	for i in range(m):
		if len(o) == n:
			break
		if b[i] not in [x[0] for x in o]:
			o.append((b[i], w[b[i]]))
	s = 0
	for i in range(m):
		ind = [o[i][0] for i in range(len(o))].index(b[i])
		s += sum([o[i][1] for i in range(ind)])
		el = o.pop(ind)
		o.insert(0, el)
	print(s)

def __starting_point():
	main()
__starting_point()


(n, m) = list(map(int, input().split()))
w = list(map(int, input().split()))
l = list(map(int, input().split()))
k = 0
f = []
for x in l:
	x -= 1
	if x not in f:
		for y in f:
			k += w[y]
		f = [x] + f
	else:
		for i in range(len(f)):
			if f[i] != x:
				k += w[f[i]]
			else:
				break
		del f[i]
		f = [x] + f
print(k)


from itertools import permutations as perm

def weigh(seq, order_seq):
	ret = 0
	w_seq = list(seq[:])
	for (idx, i) in enumerate(order_seq):
		for book_idx in w_seq[:w_seq.index(i)]:
			ret += weights[book_idx - 1]
		w_seq.insert(0, w_seq.pop(w_seq.index(i)))
	return ret
(n, m) = tuple(map(int, input().split(' ')))
weights = tuple(map(int, input().split(' ')))
order = tuple(map(int, input().split(' ')))
already = []
for i in order:
	if i not in already:
		already.append(i)
print(weigh(already, order))


(n, m) = map(int, input().split())
w = [0] + [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
lst = []
sett = set()
for i in b:
	if i not in sett:
		sett.add(i)
		lst.append(i)
lifts = 0
for i in b:
	for j in range(n):
		if lst[j] == i:
			lst.insert(0, lst[j])
			del lst[j + 1]
			break
		else:
			lifts += w[lst[j]]
print(lifts)


def ans():
	(n, m) = [int(i) for i in input().split()]
	w = [int(i) for i in input().split()]
	b = [int(i) for i in input().split()]
	books = []
	for i in b:
		if i not in books:
			books.append(i)
	ans = 0
	for i in b:
		arr = books[:books.index(i)]
		for j in arr:
			ans += w[j - 1]
		books.remove(i)
		books.insert(0, i)
	print(ans)
	return
ans()


(n, m) = map(int, input().split())
w = [0] + list(map(int, input().split()))
(t, p) = ([], [0] * (n + 1))
s = 0
for i in map(int, input().split()):
	if p[i]:
		k = t.index(i)
		s += sum((w[j] for j in t[k + 1:]))
		t.append(t.pop(k))
	else:
		s += sum((w[j] for j in t))
		t.append(i)
		p[i] = 1
print(s)


(books, reads) = list(map(int, input().split()))
booksw = list(map(int, input().split()))
readl = list(map(int, input().split()))
res = []
for b in readl:
	if b not in res:
		res.append(b)
sum = 0
for l in readl:
	for b in res:
		if b == l:
			res.remove(b)
			poped = b
			break
		sum = sum + booksw[b - 1]
	res = [poped] + res
print(sum)


(n, m) = map(int, input().split())
w = list(map(int, input().split()))
b = list(map(int, input().split()))
ans = 0
for i in range(m):
	flag = dict()
	for j in range(i - 1, -1, -1):
		if b[j] == b[i]:
			break
		if flag.get(b[j], True):
			ans += w[b[j] - 1]
			flag[b[j]] = False
print(ans)


(n, m) = map(int, input().split())
w = list(map(int, input().split()))
b = list(map(int, input().split()))
ans = list()
used = [False] * (n + 1)
for i in range(len(b)):
	if not used[b[i]]:
		ans.append(b[i])
		used[b[i]] = True
anss = 0
for i in range(len(b)):
	top = -1
	for j in range(len(ans)):
		if ans[j] == b[i]:
			top = ans[j]
			for k in range(j, 0, -1):
				ans[k] = ans[k - 1]
				anss += w[ans[k - 1] - 1]
			break
	ans[0] = top
print(anss)


from collections import defaultdict, Counter, deque
import os
import sys
from io import BytesIO, IOBase
ii = lambda : int(input())
lmii = lambda : list(map(int, input().split()))
slmii = lambda : sorted(map(int, input().split()))
li = lambda : list(input())
mii = lambda : map(int, input().split())
msi = lambda : map(str, input().split())

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

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

def main():
	(n, m) = mii()
	(w, b, o, c, s) = (lmii(), lmii(), deque(), defaultdict(int), 0)
	for i in range(m):
		if not c[b[i]]:
			o.append(b[i])
			c[b[i]] = 1
	for i in range(m):
		ind = o.index(b[i])
		for j in range(ind):
			s += w[o[j] - 1]
		val = o[ind]
		o.remove(val)
		o.appendleft(val)
	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')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


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


(n, m) = map(int, input().split())
wi = list(map(int, input().split()))
bi = list(map(int, input().split()))
ai = [-1] * n
ai2 = [-1] * n
num = 0
for i in range(m):
	bi[i] -= 1
	if ai[bi[i]] == -1:
		ai[bi[i]] = 1
		ai2[num] = bi[i]
		num += 1
for i in range(n):
	if ai[i] == -1:
		ai2[num] = i
		num += 1
ans = 0
for i in range(m):
	j = 0
	num = ai2[0]
	while j < n:
		num2 = ai2[j]
		ai2[j] = num
		num = num2
		if num == bi[i]:
			ai2[0] = num
			break
		ans += wi[num]
		j += 1
print(ans)


(n, m) = list(map(int, input().split()))
w = list(map(int, input().split()))
b = list(map(int, input().split()))
when = []
j = n + m
for i in range(n):
	try:
		j = b.index(i + 1)
	except:
		pass
	if j != n + m:
		when.append([j, i])
	j = n + m
when = list(sorted(when))
stack = []
for i in range(len(when)):
	stack.append(when[i][1])
count = 0
where = n + m
for i in range(m):
	where = stack.index(b[i] - 1)
	for j in range(where):
		count += w[stack[j]]
	stack = [stack[where]] + stack[:where] + stack[where + 1:]
print(count)


def main():
	input()
	ww = list(map(int, input().split()))
	bb = [int(_) - 1 for _ in input().split()]
	aa = []
	for i in bb:
		if i not in aa:
			aa.append(i)
	aa.reverse()
	tot = 0
	for b in bb:
		idx = aa.index(b)
		del aa[idx]
		tot += sum([ww[_] for _ in aa[idx:]])
		aa.append(b)
	print(tot)

def __starting_point():
	main()
__starting_point()


def main():
	(n, m) = read()
	w = read()
	b = read()
	bookset = set(range(1, n + 1))
	print(solve(b, w, bookset, n))

def solve(b, w, bookset, n):
	if len(b) <= 1:
		return 0
	used = [0] * (n + 1)
	sm = 0
	for i in range(len(b)):
		if not used[b[i]]:
			sm += 1
		if sm == len(bookset):
			res = solve(b[:i], w, bookset - {b[i]}, n)
			for j in range(i, len(b)):
				for k in range(n + 1):
					if used[k] > used[b[j]]:
						res += w[k - 1]
				used[b[j]] = j + 1
			return res
		used[b[i]] = i + 1
	bookset = set(filter(lambda x: x, used))
	return solve(b, w, bookset, n)

def read(mode=2):
	inputs = input().strip()
	if mode == 0:
		return inputs
	if mode == 1:
		return inputs.split()
	if mode == 2:
		return list(map(int, inputs.split()))

def write(s='\n'):
	if s is None:
		s = ''
	if isinstance(s, list):
		s = ' '.join(map(str, s))
	s = str(s)
	print(s, end='')
write(main())


N_M = list(map(int, input().split()))
Weights = list(map(int, input().split()))
Good_Books = list(map(int, input().split()))
Times = []
Count = sum(N_M)
for I in range(N_M[0]):
	try:
		Count = Good_Books.index(I + 1)
	except ValueError:
		pass
	if not Count == sum(N_M):
		Times.append([Count, I])
	Count = sum(N_M)
Times.sort()
Times = list(Times)
Heap = []
for I in range(len(Times)):
	Heap.append(Times[I][1])
Count = 0
Positions = sum(N_M)
for I in range(N_M[1]):
	Positions = Heap.index(Good_Books[I] - 1)
	for I_2 in range(Positions):
		Count += Weights[Heap[I_2]]
	Heap = [Heap[Positions]] + Heap[:Positions] + Heap[Positions + 1:]
print(Count)


from collections import deque

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

def main(ws, ords):
	stack = []
	seen = set()
	for o in ords:
		if o not in seen:
			stack.append(o)
			seen.add(o)
		if len(stack) == len(ws):
			break
	s = 0
	for o in ords:
		idx = stack.index(o)
		w = [ws[b - 1] for b in stack[:idx]]
		s += sum(w)
		stack.insert(0, stack.pop(idx))
	print(s)

def parse():
	_ = intput()
	ws = intput()
	ords = intput()
	return (ws, ords)
main(*parse())


line = input().split()
n = int(line[0])
m = int(line[1])
W = [int(w) for w in input().split()]
B = [int(b) for b in input().split()]
ans = 0
lst = [0 for i in range(n)]
for i in range(m):
	arr = list(lst)
	for j in range(i):
		if B[i - j - 1] == B[i]:
			break
		arr[B[i - j - 1] - 1] = 1
	for i in range(n):
		if arr[i] == 1:
			ans += W[i]
print(ans)


from itertools import permutations
from collections import defaultdict
from math import *
import os
import sys
from io import BytesIO, IOBase
from heapq import nlargest
from bisect import *
import copy
import itertools
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 calc(pos):
	val = 0
	poss = ans.index(pos)
	for i in range(poss):
		val += arr[ans[i] - 1]
	temp = ans[poss]
	for i in range(poss, 0, -1):
		ans[i] = ans[i - 1]
	ans[0] = temp
	return val
(n, m) = map(int, input().split())
arr = list(map(int, input().split()))
brr = list(map(int, input().split()))
d = defaultdict(int)
ans = []
for i in range(len(brr)):
	if d[brr[i]] == 0:
		ans.append(brr[i])
		d[brr[i]] = 1
exp = sum(arr)
for i in range(n):
	if d[i + 1] == 0:
		exp -= arr[i]
anss = 0
for i in range(m):
	anss += calc(brr[i])
print(anss)


(n, m) = map(int, input().split())
weight = [int(i) for i in input().split()]
order = [int(i) for i in input().split()]
stack = []
for i in order:
	if i - 1 not in stack:
		stack.append(i - 1)
ans = 0
for i in order:
	currlift = sum((weight[i] for i in stack[0:stack.index(i - 1)]))
	ans += currlift
	temp = i - 1
	stack.remove(i - 1)
	stack.insert(0, temp)
print(ans)


(n, m) = map(int, input().split())
w = list(map(int, input().split()))
b = list(map(int, input().split()))
b = list(map(lambda x: x - 1, b))
acc = [[0] for _ in range(n)]
for i in range(n):
	for j in range(m):
		acc[i].append(acc[i][-1] + (1 if b[j] == i else 0))
ans = 0
for i in range(n):
	ids = []
	for j in range(m):
		if b[j] == i:
			ids.append(j)
	ids.append(m)
	for j in range(len(ids) - 1):
		cnt = 0
		for k in range(n):
			if acc[k][ids[j + 1]] - acc[k][ids[j] + 1] >= 1:
				cnt += 1
		ans += cnt * w[i]
print(ans)


a = list(map(int, input().split()))
b = list(map(int, input().split()))
c = list(map(int, input().split()))
b.insert(0, 0)
c.insert(0, 0)
co = 0
for i in range(1, a[1] + 1):
	flag = [0 for i in range(max(c) + 1)]
	for j in range(i - 1, 0, -1):
		if c[i] == c[j]:
			break
		if flag[c[j]] == 0:
			flag[c[j]] = 1
			co += b[c[j]]
print(co)


input()
w = list(map(int, input().split()))
b = list(map(int, input().split()))
a = []
ans = 0
for x in b:
	x -= 1
	cur_sum = 0
	for (i, num) in enumerate(a):
		if num == x:
			a = [num] + a[:i] + a[i + 1:]
			break
		cur_sum += w[num]
	else:
		a = [x] + a
	ans += cur_sum
print(ans)


__author__ = 'Rakshak.R.Hegde'
from collections import deque
from bisect import bisect

def mint():
	return map(int, input().split())
(n, m) = mint()
w = tuple(mint())
b = mint()
stack = []
lifts = 0
for x in b:
	for (i, v) in enumerate(stack):
		if v == x:
			stack.pop(i)
			break
	else:
		i = 0
	for i in range(i, len(stack)):
		lifts += w[stack[i] - 1]
	stack.append(x)
print(lifts)


def K3():
	(n, m) = [int(x) for x in input().split()]
	weights = [int(x) for x in input().split()]
	readings = [int(x) - 1 for x in input().split()]
	weights += [0]
	ans = 0
	for i in range(m):
		for j in range(i - 1, -1, -1):
			if readings[j] == readings[i]:
				readings[j] = n
				break
			ans += weights[readings[j]]
	print(ans)
K3()


from __future__ import print_function
from collections import *
from sys import stdin
from heapq import *
from math import *
g = lambda : stdin.readline().strip()
gl = lambda : g().split()
gil = lambda : [int(var) for var in gl()]
gfl = lambda : [float(var) for var in gl()]
gcl = lambda : list(g())
gbs = lambda : [int(var) for var in g()]
rr = lambda x: reversed(range(x))
mod = int(1000000000.0) + 7
inf = float('inf')
(n, m) = gil()
wt = [0] + gil()
toAdd = set(range(1, n + 1))
ans = []
bk = []
for b in gil():
	bk.append(b)
	if b in toAdd:
		toAdd.remove(b)
		ans.append(b)
ans.reverse()
r = []
total = 0
for b in bk:
	while ans[-1] != b:
		total += wt[ans[-1]]
		r.append(ans.pop())
	ans.pop()
	while r:
		ans.append(r.pop())
	ans.append(b)
print(total)


(n, m) = [int(x) for x in input().split()]
w = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
ans = 0
state = [0] * n
used = [0] * n
ptr = 0
for i in b:
	if not used[i - 1]:
		used[i - 1] = 1
		state[ptr] = (i, w[i - 1])
		ptr += 1
for i in b:
	ind = state.index((i, w[i - 1]))
	ans += sum((x[1] for x in state[:ind]))
	state = [state[ind]] + state[:ind] + state[ind + 1:]
print(ans)


(books, days) = map(int, input().split())
weights = input().split()
weights = list(map(int, weights))
order = input().split()
order = list(map(int, order))
setOrder = list(dict.fromkeys(order))
booksAndWeights = dict()
for a in range(len(weights)):
	booksAndWeights[a + 1] = weights[a]
for x in range(len(setOrder)):
	weights[x] = setOrder[x]
finalCounter = 0
for b in order:
	index = 0
	while weights[index] != b:
		finalCounter = finalCounter + booksAndWeights[weights[index]]
		index += 1
	weights.insert(0, weights.pop(index))
print(finalCounter)


rd = lambda : map(int, input().split())
(n, m) = rd()
(w, b) = (list(rd()), list(rd()))
ans = 0
for i in range(m):
	j = i - 1
	viz = [0] * n
	while j >= 0 and b[j] != b[i]:
		if viz[b[j] - 1] == 0:
			viz[b[j] - 1] = 1
			ans += w[b[j] - 1]
		j -= 1
print(ans)


import sys
sys.setrecursionlimit(10 ** 9)
(n, m) = map(int, input().split())
w = [int(i) for i in input().split()]
arr = [int(i) - 1 for i in input().split()]
v = []
s = 0
used = [False] * n
for i in range(m):
	if not used[arr[i]]:
		used[arr[i]] = True
		v.append(arr[i])
for i in range(m):
	j = 0
	while v[j] != arr[i]:
		s += w[v[j]]
		j += 1
	v = [v[j]] + v[0:j] + v[j + 1:]
print(s)


(n, m) = (int(x) for x in input().split())
w = [int(x) for x in input().split()]
b = [int(x) - 1 for x in input().split()]
visited = [False] * n
stack = []
for book in b:
	if not visited[book]:
		stack.append(book)
		visited[book] = True
stack.reverse()
total_weight = 0
for reading in b:
	p = len(stack) - 1
	while stack[p] != reading:
		total_weight += w[stack[p]]
		p -= 1
	else:
		stack.__delitem__(p)
		stack.append(reading)
print(total_weight)


(n, m) = [int(i) for i in input().split()]
w = [0] + [int(i) for i in input().split()]
b = [int(i) for i in input().split()]
books = []
for book in b:
	if book not in books:
		books.append(book)
books.reverse()
ans = 0
for book in b:
	index = books.index(book)
	ans += sum([w[i] for i in books[index + 1:]])
	del books[index]
	books.append(book)
print(ans)


(n, m) = map(int, input().split())
w = list(map(int, input().split()))
b = list(map(int, input().split()))
A = 0
for i in range(m):
	(d, j) = ({}, i - 1)
	while j >= 0 and b[j] != b[i]:
		if d.get(b[j], 1):
			A += w[b[j] - 1]
			d[b[j]] = 0
		j -= 1
print(A)


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

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')
ALPHA = 'abcdefghijklmnopqrstuvwxyz'
M = 1000000007
EPS = 1e-06

def Ceil(a, b):
	return a // b + int(a % b > 0)

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()]
(n, m) = value()
w = array()
a = array()
ans = 0
for i in range(m):
	have = set()
	j = i - 1
	while j >= 0 and a[j] != a[i]:
		have.add(a[j])
		j -= 1
	for j in have:
		ans += w[j - 1]
print(ans)


def f(s):
	return int(s) - 1
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(f, input().split()))
c = [[0] * n for i in range(n)]
o = 0
for i in range(m):
	for j in range(n):
		if j != b[i]:
			c[j][b[i]] = 1
	for j in range(n):
		if c[b[i]][j] == 1:
			o += a[j]
		c[b[i]][j] = 0
print(o)


(n, m) = list(map(int, input().split()))
a = list(map(int, input().split()))
b = list(map(int, input().split()))
c = set()
l = 0
d = []
for i in range(m):
	if b[i] in c:
		k = len(d)
		j = 0
		while j < k:
			if d[j] != b[i]:
				l += a[d[j] - 1]
				j += 1
			else:
				break
		d = [b[i]] + d[0:j] + d[j + 1:]
	else:
		for j in d:
			l += a[j - 1]
		d = [b[i]] + d
		c.add(b[i])
print(l)


from bisect import *
from collections import *
from math import gcd, ceil, sqrt, floor, inf
from heapq import *
from itertools import *
from operator import add, mul, sub, xor, truediv, floordiv
from functools import *
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())
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
farr = [1]
ifa = []

def fact(x, mod=0):
	if mod:
		while x >= len(farr):
			farr.append(farr[-1] * len(farr) % mod)
	else:
		while x >= len(farr):
			farr.append(farr[-1] * len(farr))
	return farr[x]

def ifact(x, mod):
	global ifa
	ifa.append(pow(farr[-1], mod - 2, mod))
	for i in range(x, 0, -1):
		ifa.append(ifa[-1] * i % mod)
	ifa = ifa[::-1]

def per(i, j, mod=0):
	if i < j:
		return 0
	if not mod:
		return fact(i) // fact(i - j)
	return farr[i] * ifa[i - j] % mod

def com(i, j, mod=0):
	if i < j:
		return 0
	if not mod:
		return per(i, j) // fact(j)
	return per(i, j, mod) * ifa[j] % mod

def catalan(n):
	return com(2 * n, n) // (n + 1)

def linc(f, t, l, r):
	while l < r:
		mid = (l + r) // 2
		if t > f(mid):
			l = mid + 1
		else:
			r = mid
	return l

def rinc(f, t, l, r):
	while l < r:
		mid = (l + r + 1) // 2
		if t < f(mid):
			r = mid - 1
		else:
			l = mid
	return l

def ldec(f, t, l, r):
	while l < r:
		mid = (l + r) // 2
		if t < f(mid):
			l = mid + 1
		else:
			r = mid
	return l

def rdec(f, t, l, r):
	while l < r:
		mid = (l + r + 1) // 2
		if t > f(mid):
			r = mid - 1
		else:
			l = mid
	return l

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

def binfun(x):
	c = 0
	for w in arr:
		c += ceil(w / x)
	return c

def lowbit(n):
	return n & -n

def inverse(a, m):
	a %= m
	if a <= 1:
		return a
	return (1 - inverse(m, a) * m) // a % m

class BIT:

	def __init__(self, arr):
		self.arr = arr
		self.n = len(arr) - 1

	def update(self, x, v):
		while x <= self.n:
			self.arr[x] += v
			x += x & -x

	def query(self, x):
		ans = 0
		while x:
			ans += self.arr[x]
			x &= x - 1
		return ans

class SMT:

	def __init__(self, arr):
		self.n = len(arr) - 1
		self.arr = [0] * (self.n << 2)
		self.lazy = [0] * (self.n << 2)

		def Build(l, r, rt):
			if l == r:
				self.arr[rt] = arr[l]
				return
			m = l + r >> 1
			Build(l, m, rt << 1)
			Build(m + 1, r, rt << 1 | 1)
			self.pushup(rt)
		Build(1, self.n, 1)

	def pushup(self, rt):
		self.arr[rt] = self.arr[rt << 1] + self.arr[rt << 1 | 1]

	def pushdown(self, rt, ln, rn):
		if self.lazy[rt]:
			self.lazy[rt << 1] += self.lazy[rt]
			self.lazy[rt << 1 | 1] = self.lazy[rt]
			self.arr[rt << 1] += self.lazy[rt] * ln
			self.arr[rt << 1 | 1] += self.lazy[rt] * rn
			self.lazy[rt] = 0

	def update(self, L, R, c, l=1, r=None, rt=1):
		if r == None:
			r = self.n
		if L <= l and r <= R:
			self.arr[rt] += c * (r - l + 1)
			self.lazy[rt] += c
			return
		m = l + r >> 1
		self.pushdown(rt, m - l + 1, r - m)
		if L <= m:
			self.update(L, R, c, l, m, rt << 1)
		if R > m:
			self.update(L, R, c, m + 1, r, rt << 1 | 1)
		self.pushup(rt)

	def query(self, L, R, l=1, r=None, rt=1):
		if r == None:
			r = self.n
		if L <= l and R >= r:
			return self.arr[rt]
		m = l + r >> 1
		self.pushdown(rt, m - l + 1, r - m)
		ans = 0
		if L <= m:
			ans += self.query(L, R, l, m, rt << 1)
		if R > m:
			ans += self.query(L, R, m + 1, r, rt << 1 | 1)
		return ans

class DSU:

	def __init__(self, n):
		self.c = [-1] * n

	def same(self, x, y):
		return self.find(x) == self.find(y)

	def find(self, x):
		if self.c[x] < 0:
			return x
		self.c[x] = self.find(self.c[x])
		return self.c[x]

	def union(self, u, v):
		(u, v) = (self.find(u), self.find(v))
		if u == v:
			return False
		if self.c[u] < self.c[v]:
			(u, v) = (v, u)
		self.c[u] += self.c[v]
		self.c[v] = u
		return True

	def size(self, x):
		return -self.c[self.find(x)]

class UFS:

	def __init__(self, n):
		self.parent = [i for i in range(n)]
		self.ranks = [0] * n

	def find(self, x):
		if x != self.parent[x]:
			self.parent[x] = self.find(self.parent[x])
		return self.parent[x]

	def union(self, u, v):
		(pu, pv) = (self.find(u), self.find(v))
		if pu == pv:
			return False
		if self.ranks[pu] >= self.ranks[pv]:
			self.parent[pv] = pu
			if self.ranks[pv] == self.ranks[pu]:
				self.ranks[pu] += 1
		else:
			self.parent[pu] = pv

def Prime(n):
	c = 0
	prime = []
	flag = [0] * (n + 1)
	for i in range(2, n + 1):
		if not flag[i]:
			prime.append(i)
			c += 1
		for j in range(c):
			if i * prime[j] > n:
				break
			flag[i * prime[j]] = prime[j]
			if i % prime[j] == 0:
				break
	return prime

def dij(s, graph):
	d = {}
	d[s] = 0
	heap = [(0, s)]
	seen = set()
	while heap:
		(dis, u) = heappop(heap)
		if u in seen:
			continue
		for v in graph[u]:
			if v not in d or d[v] > d[u] + graph[u][v]:
				d[v] = d[u] + graph[u][v]
				heappush(heap, (d[v], v))
	return d

def GP(it):
	return [(ch, len(list(g))) for (ch, g) in groupby(it)]

class DLN:

	def __init__(self, val):
		self.val = val
		self.pre = None
		self.next = None
t = 1
for i in range(t):
	(n, m) = RL()
	w = RLL()
	b = RLL()
	ans = 0
	vis = [0] * (n + 1)
	res = []
	for i in range(m):
		if not vis[b[i]]:
			res.append(b[i])
			vis[b[i]] = 1
	res = res[::-1]
	for i in range(m):
		for j in range(len(res) - 1, -1, -1):
			if res[j] != b[i]:
				ans += w[res[j] - 1]
			else:
				res.pop(j)
				res.append(b[i])
				break
	print(ans)


(n, m) = map(int, input().split())
w = [-1] + list(map(int, input().split()))
b = list(map(int, input().split()))
stack = []
used = set()
for i in range(m):
	if not b[i] in used:
		stack.append(b[i])
		used.add(b[i])
for i in range(1, n + 1):
	if i not in used:
		stack.append(i)
		used.add(i)
ans = 0
for i in range(m):
	bb = b[i]
	s = 0
	for j in range(n):
		if bb != stack[j]:
			s += w[stack[j]]
		else:
			stack = [stack[j]] + stack[:j] + stack[j + 1:]
			ans += s
			break
print(ans)