At the big break Nastya came to the school dining room. There are $n$ pupils in the school, numbered from $1$ to $n$. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.

Formally, there are some pairs $u$, $v$ such that if the pupil with number $u$ stands directly in front of the pupil with number $v$, Nastya can ask them and they will change places. 

Nastya asks you to find the maximal number of places in queue she can move forward. 


-----Input-----

The first line contains two integers $n$ and $m$ ($1 \leq n \leq 3 \cdot 10^{5}$, $0 \leq m \leq 5 \cdot 10^{5}$) — the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second.

The second line contains $n$ integers $p_1$, $p_2$, ..., $p_n$ — the initial arrangement of pupils in the queue, from the queue start to its end ($1 \leq p_i \leq n$, $p$ is a permutation of integers from $1$ to $n$). In other words, $p_i$ is the number of the pupil who stands on the $i$-th position in the queue.

The $i$-th of the following $m$ lines contains two integers $u_i$, $v_i$ ($1 \leq u_i, v_i \leq n, u_i \neq v_i$), denoting that the pupil with number $u_i$ agrees to change places with the pupil with number $v_i$ if $u_i$ is directly in front of $v_i$. It is guaranteed that if $i \neq j$, than $v_i \neq v_j$ or $u_i \neq u_j$. Note that it is possible that in some pairs both pupils agree to change places with each other.

Nastya is the last person in the queue, i.e. the pupil with number $p_n$.


-----Output-----

Print a single integer — the number of places in queue she can move forward.


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

Output
1
Input
3 3
3 1 2
1 2
3 1
3 2

Output
2
Input
5 2
3 1 5 4 2
5 2
5 4

Output
1


-----Note-----

In the first example Nastya can just change places with the first pupil in the queue.

Optimal sequence of changes in the second example is   change places for pupils with numbers $1$ and $3$.  change places for pupils with numbers $3$ and $2$.  change places for pupils with numbers $1$ and $2$. 

The queue looks like $[3, 1, 2]$, then $[1, 3, 2]$, then $[1, 2, 3]$, and finally $[2, 1, 3]$ after these operations.

Difficulty: MEDIUM_HARD
Tags: Greedy algorithms
Skill types: Greedy algorithms

Starter code:

Solutions:
import sys
import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def main():
	(n, m) = map(int, input().split())
	P = list(map(int, input().split()))
	P = [p - 1 for p in P]
	x = P[-1]
	g = [[] for i in range(n)]
	for i in range(m):
		(u, v) = map(int, input().split())
		(u, v) = (u - 1, v - 1)
		g[u].append(v)
	if n == 1:
		print(0)
		exit()
	S = P[0:-1]
	ans = 0
	Q = {x}
	while S:
		y = S[-1]
		cnt = 0
		for z in g[y]:
			if z in Q:
				cnt += 1
		if cnt == len(Q):
			ans += 1
		else:
			Q.add(y)
		S.pop()
	print(ans)
main()


(n, m) = map(int, input().split())
g = [int(g) for g in input().split()]
swap = set()
last = {g[-1]}
for i in range(m):
	swap.add(tuple(map(int, input().split())))
g = g[::-1]
for pupil in g[1:]:
	for x in last:
		if (pupil, x) not in swap:
			last.add(pupil)
			break
print(n - len(last))


import os
s = os.read(0, os.fstat(0).st_size)
inp = []
numb = 0
for i in range(len(s)):
	if s[i] >= 48:
		numb = 10 * numb + s[i] - 48
	elif s[i] != 13:
		inp.append(numb)
		numb = 0
		sign = 1
if s[-1] >= 48:
	inp.append(numb)
ii = 0
(n, m) = (inp[ii], inp[ii + 1])
ii += 2
a = inp[ii:ii + n]
last = a.pop()
ii += n
friend = [[] for i in range(n + 1)]
for _ in range(m):
	(u, v) = (inp[ii], inp[ii + 1])
	ii += 2
	friend[u].append(v)
mark = [0] * (n + 1)
mark[last] = 1
req = 1
ans = 0
for i in range(n - 2, -1, -1):
	u = a[i]
	cnt = sum((mark[v] for v in friend[u]))
	if cnt == req:
		ans += 1
	else:
		mark[u] = 1
		req += 1
print(ans)


(n, m) = map(int, input().split())
p = list([int(s) - 1 for s in input().split()])
nastya = p[-1]
good = [False] * n
swaps = [[] for _ in range(n)]
counts = [0] * n
for _ in range(m):
	(u, v) = map(int, input().split())
	u -= 1
	v -= 1
	if v == nastya:
		good[u] = True
	else:
		swaps[v].append(u)
total = 0
bad_count = 0
for (i, pupil) in enumerate(p[-2::-1]):
	if good[pupil] and counts[pupil] >= bad_count:
		total += 1
	else:
		bad_count += 1
		for u in swaps[pupil]:
			counts[u] += 1
print(total)


import sys
from collections import defaultdict

def move(arr, l, num, i):
	for j in range(i, n - 1):
		if arr[j + 1] in l:
			(arr[j + 1], arr[j]) = (arr[j], arr[j + 1])
		else:
			return
(n, m) = map(int, sys.stdin.readline().split())
arr = list(map(int, sys.stdin.readline().split()))
graph1 = defaultdict(set)
for i in range(m):
	(u, v) = map(int, sys.stdin.readline().split())
	graph1[u].add(v)
num = arr[n - 1]
for i in range(n - 1, -1, -1):
	move(arr, graph1[arr[i]], arr[i], i)
for i in range(n):
	if arr[i] == num:
		break
print(n - 1 - i)


import sys
sys.setrecursionlimit(20000000)
input = sys.stdin.readline
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
for i in range(n):
	a[i] -= 1
b = [list(map(int, input().split())) for i in range(m)]
na = a[-1]
g = [set() for i in range(n)]
nani = set()
for (i, j) in b:
	i -= 1
	j -= 1
	g[i].add(j)
	if j == na:
		nani.add(i)
ans = 0
usi = set()
for i in range(n - 2, -1, -1):
	if a[i] in nani:
		if len(g[a[i]]) == len(g[a[i]].union(usi)):
			ans += 1
		else:
			usi.add(a[i])
	else:
		usi.add(a[i])
print(ans)


import sys
input = sys.stdin.readline
print = sys.stdout.write
(n, m) = map(int, input().split())
q = list(map(int, input().split()))
pos = {}
for i in range(n):
	pos[q[i] - 1] = i
drt = {}
for i in range(n):
	drt[i] = 0
part = set()
for i in range(m):
	(u, v) = map(int, input().split())
	if pos[u - 1] < pos[v - 1]:
		drt[u - 1] += 1
	if v == q[-1]:
		part.add(pos[u - 1])
b = [0 for i in range(n)]
for i in part:
	b[i] = 1
ans = 0
l = 0
for i in range(n - 1, -1, -1):
	if b[i] == 1 and drt[q[i] - 1] >= n - 1 - pos[q[i] - 1] - l:
		l += 1
		ans += 1
print(str(ans))


import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
from collections import defaultdict
from itertools import permutations
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')
(n, m) = map(int, input().split())
p = list(map(int, input().split()))
ok = [set() for _ in range(n + 1)]
for _ in range(m):
	(u, v) = map(int, input().split())
	ok[u].add(v)
ans = 0
s = {p[n - 1]}
for i in range(n - 2, -1, -1):
	if s <= ok[p[i]]:
		ans += 1
	else:
		s.add(p[i])
print(ans)


from collections import deque, Counter, OrderedDict
from heapq import nsmallest, nlargest, heapify, heappop, heappush, heapreplace
from math import ceil, floor, log, log2, sqrt, gcd, factorial, pow, pi
from bisect import bisect_left, bisect_right
import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def binNumber(n, size=4):
	return bin(n)[2:].zfill(size)

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

def ini():
	return int(input())

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

def sti():
	return str(input())

def par(a):
	print(' '.join(list(map(str, a))))

def tdl(outerListSize, innerListSize, defaultValue=0):
	return [[defaultValue] * innerListSize for i in range(outerListSize)]

def sts(s):
	s = list(s)
	s.sort()
	return ''.join(s)

def bis(a, x):
	i = bisect_left(a, x)
	if i != len(a) and a[i] == x:
		return [i, True]
	else:
		return [-1, False]

class pair:

	def __init__(self, f, s):
		self.fi = f
		self.se = s

	def __lt__(self, other):
		return (self.fi, self.se) < (other.fi, other.se)
(n, m) = isp()
a = iar()
k = a[n - 1]
p = tdl(n + 1, 0)
c = []
for i in range(m):
	(x, y) = isp()
	p[x].append(y)
for i in range(n + 1):
	p[i].sort()
	c.append(Counter(p[i]))
q = []
i = n - 1
while i > 0:
	i -= 1
	if bis(p[a[i]], k)[1]:
		sw = True
		for j in q:
			if c[a[i]][j] == 0:
				sw = False
				break
		if not sw:
			q.append(a[i])
	else:
		q.append(a[i])
print(n - 1 - len(q))


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
kek = set()
p = {a[-1]}
for i in range(m):
	kek.add(tuple(map(int, input().split())))
a = a[::-1]
for c in a[1:]:
	f = True
	for x in p:
		if (c, x) not in kek:
			p.add(c)
			break
print(n - len(p))


(n, m) = list(map(int, input().split()))
p = list(map(int, input().split()))
p.insert(0, 0)
vis = [0] * (n + 7)
G = [[0] for i in range(n + 7)]
for i in range(m):
	(u, v) = list(map(int, input().split()))
	G[v].append(u)
for x in G[p[n]]:
	vis[x] += 1
ans = 0
cnt = 1
for i in range(n - 1, 0, -1):
	now = p[i]
	if vis[now] == cnt:
		ans += 1
	else:
		cnt += 1
		for y in G[now]:
			vis[y] += 1
print(ans)


(n, m) = list(map(int, input().split()))
q = list(map(int, input().split()))
G = [set() for _ in range(n + 1)]
vn = []
for i in range(m):
	(u, v) = list(map(int, input().split()))
	G[u].add(v)
P = set([q[-1]])
for i in range(n - 2, -1, -1):
	p = q[i]
	if len(G[p]) < len(P) or not P.issubset(G[p]):
		P.add(p)
print(n - len(P))


(n, m) = [int(x) for x in input().split()]
q = [int(x) for x in input().split()]
helpers = [[] for i in range(n + 5)]
helping = [0] * 300005
(ans, removed) = (0, 0)
for i in range(m):
	(u, v) = [int(c) for c in input().split()]
	helpers[v].append(u)
for i in helpers[q[-1]]:
	helping[i] += 1
for i in range(n - 2, -1, -1):
	remaining = n - 1 - i - removed
	if helping[q[i]] == remaining:
		removed += 1
		ans += 1
	else:
		for k in helpers[q[i]]:
			helping[k] += 1
print(ans)


import os
import sys
from bisect import bisect_left, bisect_right
from collections import Counter, defaultdict
from functools import reduce
from io import BytesIO, IOBase
from itertools import combinations
from math import gcd, inf, sqrt, ceil, floor

def lcm(a, b):
	return a * b // gcd(a, b)
MAXN = 1000004
spf = [0 for i in range(MAXN)]

def 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(sqrt(MAXN))):
		if spf[i] == i:
			for j in range(i * i, MAXN, i):
				if spf[j] == j:
					spf[j] = i

def getFactorization(x):
	ret = Counter()
	while x != 1:
		ret[spf[x]] += 1
		x = x // spf[x]
	return ret

def printDivisors(n):
	i = 2
	z = [1, n]
	while i <= sqrt(n):
		if n % i == 0:
			if n / i == i:
				z.append(i)
			else:
				z.append(i)
				z.append(n // i)
		i = i + 1
	return z

def create(n, x, f):
	pq = len(bin(n)[2:])
	if f == 0:
		tt = min
	else:
		tt = max
	dp = [[inf] * n for _ in range(pq)]
	dp[0] = x
	for i in range(1, pq):
		for j in range(n - (1 << i) + 1):
			dp[i][j] = tt(dp[i - 1][j], dp[i - 1][j + (1 << i - 1)])
	return dp

def enquiry(l, r, dp, f):
	if l > r:
		return inf if not f else -inf
	if f == 1:
		tt = max
	else:
		tt = min
	pq1 = len(bin(r - l + 1)[2:]) - 1
	return tt(dp[pq1][l], dp[pq1][r - (1 << pq1) + 1])

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

def main():
	from collections import Counter
	(n, m) = map(int, input().split())
	a = [int(x) for x in input().split()]
	adj = [[] for i in range(n + 1)]
	xx = a[-1]
	ind = Counter()
	for i in range(n):
		ind[a[i]] = i
	for i in range(m):
		(u, v) = map(int, input().split())
		if ind[v] > ind[u]:
			adj[v].append(u)
	s = set()
	an = 0
	vis = [0] * (n + 1)
	c = 1
	for j in adj[a[-1]]:
		vis[j] += 1
	for i in range(n - 2, -1, -1):
		if vis[a[i]] == c:
			an += 1
		else:
			for j in adj[a[i]]:
				vis[j] += 1
			c += 1
	print(an)
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
import collections
from math import floor, ceil, log2
inp = lambda : sys.stdin.readline().strip()
(n, m) = map(int, inp().split())
a = list(map(int, inp().split()))
a = [0] + list(reversed(a))
g = [[0] for i in range(n + 1)]
for i in range(m):
	(u, v) = map(int, inp().split())
	g[u].append(v)
p = [0] * (n + 1)
p[a[1]] = 1
cnt = 1
ans = 0
for i in range(2, n + 1):
	cnt2 = 0
	for to in g[a[i]]:
		if p[to] == 1:
			cnt2 += 1
	if cnt == cnt2:
		ans += 1
	else:
		p[a[i]] = 1
		cnt += 1
print(ans)


(n, m) = map(int, input().split())
p = list(map(int, input().split()))
gr = [set() for i in range(n)]
for i in range(m):
	(a, b) = map(int, input().split())
	a -= 1
	b -= 1
	gr[a].add(b)
cant = {p[-1] - 1}
for i in range(n - 2, -1, -1):
	cnt = 0
	for j in gr[p[i] - 1]:
		if j in cant:
			cnt += 1
	if cnt != len(cant):
		cant.add(p[i] - 1)
print(n - len(cant))


(n, m) = map(int, input().split())
p = [int(i) for i in input().split()]
gr = [0] * (n + 1)
for i in range(n + 1):
	gr[i] = []
for i in range(m):
	(u, v) = map(int, input().split())
	gr[u].append(v)
can = [0] * (n + 1)
can[p[n - 1]] = 1
idx = n - 2
good = 1
ans = 0
while idx >= 0:
	cur = 0
	for i in gr[p[idx]]:
		cur += can[i]
	if cur == good:
		ans += 1
	else:
		good += 1
		can[p[idx]] = 1
	idx -= 1
print(ans)


(n, m) = [int(x) for x in input().split()]
p = [int(x) - 1 for x in input().split()]
e = [[] for _ in range(n)]
for _ in range(m):
	(u, v) = [int(x) for x in input().split()]
	e[u - 1].append(v - 1)
t = [p[n - 1]]
ans = 0
for i in range(n - 2, -1, -1):
	u = p[i]
	if len(e[u]) >= len(t):
		f = set(e[u])
		can = True
		for x in t:
			if x not in f:
				can = False
				break
		if can:
			ans += 1
		else:
			t.append(u)
	else:
		t.append(u)
print(ans)


import sys
import heapq
import math
from enum import Enum
lines = sys.stdin.read().splitlines()
(n, m) = map(int, lines[0].split(' '))
positionToNumber = [int(x) - 1 for x in lines[1].split(' ')]
numberToPosition = [0] * n
for i in range(0, len(positionToNumber)):
	numberToPosition[positionToNumber[i]] = i
letsInFront = []
for i in range(0, n):
	letsInFront.append(set())
for i in range(0, m):
	(a, b) = list(map(int, lines[i + 2].split(' ')))
	indexA = a - 1
	indexB = b - 1
	letsInFront[numberToPosition[indexA]].add(numberToPosition[indexB])
count = 0
let = set()
let.add(n - 1)
for i in reversed(range(0, n - 1)):
	found = True
	if len(let) > len(letsInFront[i]):
		found = False
	else:
		for j in let:
			if j not in letsInFront[i]:
				found = False
				break
	if not found:
		let.add(i)
	else:
		count += 1
print(count)


import sys
input = sys.stdin.readline
(n, m) = list(map(int, input().split()))
P = list(map(int, input().split()))
PAIR = [list(map(int, input().split())) for i in range(m)]
NAT = P[-1]
LIST = [[] for i in range(n + 1)]
for (x, y) in PAIR:
	LIST[x].append(y)
for i in range(n + 1):
	LIST[i] = set(LIST[i])
FLIST = [NAT]
i = n - 2
ANS = 0
while i >= 0:
	for j in FLIST:
		if j in LIST[P[i]]:
			continue
		else:
			FLIST.append(P[i])
			break
	else:
		ANS += 1
	i -= 1
print(ANS)


import sys

def read():
	return sys.stdin.readline()
(n, m) = map(int, read().split())
p = [int(i) for i in read().split()]
gr = [0] * (n + 1)
for i in range(n + 1):
	gr[i] = []
for i in range(m):
	(u, v) = map(int, read().split())
	gr[u].append(v)
can = [0] * (n + 1)
can[p[n - 1]] = 1
idx = n - 2
good = 1
ans = 0
while idx >= 0:
	cur = 0
	for i in gr[p[idx]]:
		cur += can[i]
	if cur == good:
		ans += 1
	else:
		good += 1
		can[p[idx]] = 1
	idx -= 1
print(ans)


import sys
input = sys.stdin.readline
(n, m) = map(int, input().split())
p = list(map(int, input().split()))
ok = [set() for _ in range(n + 1)]
for _ in range(m):
	(u, v) = map(int, input().split())
	ok[u].add(v)
ans = 0
req = 1
mark = [0] * (n + 1)
mark[p[n - 1]] = 1
for i in range(n - 2, -1, -1):
	cnt = sum((mark[v] for v in ok[p[i]]))
	if cnt == req:
		ans += 1
	else:
		req += 1
		mark[p[i]] = 1
print(ans)


(n, m) = map(int, input().split())
p = tuple(map(int, input().split()))
r = [{i} for i in range(n + 1)]
for _ in range(m):
	(u, v) = map(int, input().split())
	r[u].add(v)
first = True
nr = set()
res = 0
for i in p[::-1]:
	if first:
		cur = 1
		first = False
	else:
		cur = len(nr)
		for ri in r[i]:
			if ri in nr:
				cur -= 1
	if cur:
		nr.add(i)
	else:
		res += 1
print(res)


from sys import stdin
(n, m) = list(map(int, stdin.readline().strip().split()))
s = list(map(int, stdin.readline().strip().split()))
nas = s[-1]
g = set()
st = set()
for i in range(m):
	(a, b) = list(map(int, stdin.readline().strip().split()))
	if b == nas:
		g.add(a)
	else:
		st.add((a, b))
x = n - 2
while x >= 0:
	if s[x] in g and s[x + 1] not in g and ((s[x], s[x + 1]) in st):
		st.remove((s[x], s[x + 1]))
		aux = s[x]
		s[x] = s[x + 1]
		s[x + 1] = aux
		x = min(n - 2, x + 1)
	elif s[x] in g and s[x + 1] in g and ((s[x], s[x + 1]) in st):
		st.remove((s[x], s[x + 1]))
		aux = s[x]
		s[x] = s[x + 1]
		s[x + 1] = aux
		x = min(n - 2, x + 1)
	else:
		x -= 1
ans = 0
for i in range(n - 2, -1, -1):
	if s[i] in g:
		ans += 1
	else:
		break
print(ans)


import os
from io import BytesIO
input = BytesIO(os.read(0, os.fstat(0).st_size)).readline
ii = lambda : int(input())
mi = lambda : map(int, input().split())
li = lambda : list(mi())
(n, m) = mi()
p = li()
ok = [set() for _ in range(n + 1)]
for _ in range(m):
	(u, v) = mi()
	ok[u].add(v)
ans = 0
req = 1
mark = [0] * (n + 1)
mark[p[n - 1]] = 1
for i in range(n - 2, -1, -1):
	cnt = sum((mark[v] for v in ok[p[i]]))
	if cnt == req:
		ans += 1
	else:
		req += 1
		mark[p[i]] = 1
print(ans)


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

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

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

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

def stringIn():
	return stdin.readline().strip()
(n, m) = listIn()
p = listIn()
pairs = set()
for i in range(m):
	(u, v) = listIn()
	pairs.add((u, v))
stack = [p[-1]]
p = p[:-1]
c = n - 1
total = 0
while c > 0:
	pupil = p.pop(-1)
	f = 1
	for ele in stack:
		if (pupil, ele) in pairs:
			continue
		else:
			f = 0
			break
	if f:
		total += 1
	else:
		stack.append(pupil)
	c -= 1
print(total)


import math
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
mod = 10 ** 9 + 7
mod1 = 998244353
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')

class TreeNode:

	def __init__(self, k, v):
		self.key = k
		self.value = v
		self.left = None
		self.right = None
		self.parent = None
		self.height = 1
		self.num_left = 1
		self.num_total = 1

class AvlTree:

	def __init__(self):
		self._tree = None

	def add(self, k, v):
		if not self._tree:
			self._tree = TreeNode(k, v)
			return
		node = self._add(k, v)
		if node:
			self._rebalance(node)

	def _add(self, k, v):
		node = self._tree
		while node:
			if k < node.key:
				if node.left:
					node = node.left
				else:
					node.left = TreeNode(k, v)
					node.left.parent = node
					return node.left
			elif node.key < k:
				if node.right:
					node = node.right
				else:
					node.right = TreeNode(k, v)
					node.right.parent = node
					return node.right
			else:
				node.value = v
				return

	@staticmethod
	def get_height(x):
		return x.height if x else 0

	@staticmethod
	def get_num_total(x):
		return x.num_total if x else 0

	def _rebalance(self, node):
		n = node
		while n:
			lh = self.get_height(n.left)
			rh = self.get_height(n.right)
			n.height = max(lh, rh) + 1
			balance_factor = lh - rh
			n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
			n.num_left = 1 + self.get_num_total(n.left)
			if balance_factor > 1:
				if self.get_height(n.left.left) < self.get_height(n.left.right):
					self._rotate_left(n.left)
				self._rotate_right(n)
			elif balance_factor < -1:
				if self.get_height(n.right.right) < self.get_height(n.right.left):
					self._rotate_right(n.right)
				self._rotate_left(n)
			else:
				n = n.parent

	def _remove_one(self, node):
		replacement = node.left or node.right
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = replacement
			else:
				node.parent.right = replacement
			replacement.parent = node.parent
			node.parent = None
		else:
			self._tree = replacement
			replacement.parent = None
		node.left = None
		node.right = None
		node.parent = None
		self._rebalance(replacement)

	def _remove_leaf(self, node):
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = None
			else:
				node.parent.right = None
			self._rebalance(node.parent)
		else:
			self._tree = None
		node.parent = None
		node.left = None
		node.right = None

	def remove(self, k):
		node = self._get_node(k)
		if not node:
			return
		if AvlTree._is_leaf(node):
			self._remove_leaf(node)
			return
		if node.left and node.right:
			nxt = AvlTree._get_next(node)
			node.key = nxt.key
			node.value = nxt.value
			if self._is_leaf(nxt):
				self._remove_leaf(nxt)
			else:
				self._remove_one(nxt)
			self._rebalance(node)
		else:
			self._remove_one(node)

	def get(self, k):
		node = self._get_node(k)
		return node.value if node else -1

	def _get_node(self, k):
		if not self._tree:
			return None
		node = self._tree
		while node:
			if k < node.key:
				node = node.left
			elif node.key < k:
				node = node.right
			else:
				return node
		return None

	def get_at(self, pos):
		x = pos + 1
		node = self._tree
		while node:
			if x < node.num_left:
				node = node.left
			elif node.num_left < x:
				x -= node.num_left
				node = node.right
			else:
				return (node.key, node.value)
		raise IndexError('Out of ranges')

	@staticmethod
	def _is_left(node):
		return node.parent.left and node.parent.left == node

	@staticmethod
	def _is_leaf(node):
		return node.left is None and node.right is None

	def _rotate_right(self, node):
		if not node.parent:
			self._tree = node.left
			node.left.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.left
			node.left.parent = node.parent
		else:
			node.parent.right = node.left
			node.left.parent = node.parent
		bk = node.left.right
		node.left.right = node
		node.parent = node.left
		node.left = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	def _rotate_left(self, node):
		if not node.parent:
			self._tree = node.right
			node.right.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.right
			node.right.parent = node.parent
		else:
			node.parent.right = node.right
			node.right.parent = node.parent
		bk = node.right.left
		node.right.left = node
		node.parent = node.right
		node.right = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	@staticmethod
	def _get_next(node):
		if not node.right:
			return node.parent
		n = node.right
		while n.left:
			n = n.left
		return n

class SegmentTree1:

	def __init__(self, data, default='z', func=lambda a, b: min(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: a + b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

def powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

def product(l):
	por = 1
	for i in range(len(l)):
		por *= l[i]
	return por

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] < key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def binary(x, length):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] >= k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater
(n, m) = map(int, input().split())
d = defaultdict(set)
l = list(map(int, input().split()))
for i in range(m):
	(a, b) = map(int, input().split())
	d[a].add(b)
cur = set()
ans = 0
for i in range(n - 2, -1, -1):
	if l[-1] in d[l[i]]:
		f = 0
		if len(cur) > len(d[l[i]]):
			cur.add(l[i])
			continue
		for j in cur:
			if j in d[l[i]]:
				continue
			else:
				f = 1
				break
		if f == 0:
			ans += 1
		else:
			cur.add(l[i])
	else:
		cur.add(l[i])
print(ans)


def readLine():
	a = input()
	return [int(i) for i in a.split(' ')]
nm = readLine()
(n, m) = (nm[0], nm[1])
a = readLine()
pos = [0 for _ in range(n + 1)]
for (i, val) in enumerate(a):
	pos[val] = i
g = [[] for _ in range(n + 1)]
for i in range(m):
	xy = readLine()
	(x, y) = (xy[0], xy[1])
	g[y].append(x)
used = [0 for _ in range(n + 1)]
used[a[n - 1]] = -1
ans = 0
l = []
for j in range(n):
	i = n - j - 1
	if used[a[i]] < len(l):
		l.append(a[i])
		for (_, val) in enumerate(g[a[i]]):
			used[val] = used[val] + 1
	else:
		ans = ans + 1
print(ans)


(n, m) = (int(x) for x in input().split())
queue = [int(x) - 1 for x in input().split()]
id___passables = [set() for _ in range(n)]
for _ in range(m):
	(id1, id2) = (int(x) - 1 for x in input().split())
	id___passables[id2].add(id1)
train_passables = id___passables[queue[-1]].copy()
ans = 0
for person in reversed(queue[:-1]):
	if person in train_passables:
		ans += 1
	else:
		train_passables &= id___passables[person]
print(ans)


import sys
input = sys.stdin.readline

def main():
	(n, m) = list(map(int, input().split()))
	p = list(map(int, input().split()))
	edge_set = set()
	for _ in range(m):
		(u, v) = list(map(int, input().split()))
		edge_set.add((u, v))
	ret = 0
	curr_list = [p.pop()]
	while p:
		u = p.pop()
		flag = True
		for v in curr_list:
			if (u, v) not in edge_set:
				flag = False
				break
		if flag:
			ret += 1
		else:
			curr_list.append(u)
	print(ret)

def __starting_point():
	main()
__starting_point()


from sys import stdin, stdout
import collections
(N, M) = [int(x) for x in stdin.readline().split()]
P = [int(x) for x in stdin.readline().split()]
idx = {}
for i in range(N):
	idx[P[i]] = i
swap = [0] * N
data = {}
for i in range(N):
	data[i] = []
for i in range(M):
	(x, y) = [int(x) for x in stdin.readline().split()]
	A = idx[x]
	B = idx[y]
	if A < B:
		swap[A] += 1
		data[B].append(A)
k = N - 1
res = 0
for i in range(N - 2, -1, -1):
	if swap[i] >= k - i:
		k -= 1
		for j in data[i]:
			swap[j] -= 1
print(N - 1 - k)


from sys import stdin, stdout
input = stdin.readline
listin = lambda : list(map(int, input().split()))
mapin = lambda : map(int, input().split())
(n, m) = mapin()
l = listin()
ha = set()
for i in range(m):
	ha.add(tuple(mapin()))
count = 0
z = l[-1]
j = n - 1
if j == 0:
	print(count)
else:
	seti = []
	while j >= 0:
		if seti == []:
			seti.append(l[j])
			j -= 1
		else:
			flag = 0
			for x in seti:
				if (l[j], x) not in ha:
					flag = 1
					break
			if flag == 0:
				j -= 1
				count += 1
			else:
				seti.append(l[j])
				j -= 1
	print(count)


(n, m) = map(int, input().split())
p = [int(i) - 1 for i in input().split()]
not_pass = set()
t = [set() for i in range(n)]
for i in range(m):
	(a, b) = map(int, input().split())
	t[a - 1].add(b - 1)
for ell in p[-2::-1]:
	k = 0
	for el in t[ell]:
		if el in not_pass:
			k += 1
	if k != len(not_pass) or p[-1] not in t[ell]:
		not_pass.add(ell)
print(n - 1 - len(not_pass))


import sys
import math
import bisect
from math import sqrt

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

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

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

def get_list():
	return list(map(int, sys.stdin.readline().strip().split()))
mod = int(1000000000.0) + 7
(n, m) = rinput()
p = [0] + get_list()
d = {i: [] for i in range(1, n + 1)}
for _ in range(m):
	(u, v) = rinput()
	d[u].append(v)
last = p[n]
target = n
for i in range(n - 1, 0, -1):
	for j in range(i, target):
		if p[j + 1] in d[p[j]]:
			(p[j], p[j + 1]) = (p[j + 1], p[j])
		else:
			break
	if p[target] != last:
		target -= 1
print(n - target)


import heapq
import sys
from collections import defaultdict, Counter
from functools import reduce
(n, m) = list(map(int, input().split()))
p = list(map(int, input().split()))
g = [list() for i in range(n + 1)]
for i in range(m):
	(a, b) = map(int, input().split())
	g[a].append(b)
used = {p[-1]}
ans = 0
for i in range(n - 2, -1, -1):
	c = 0
	for u in g[p[i]]:
		if u in used:
			c += 1
	if c == len(used):
		ans += 1
	else:
		used.add(p[i])
print(ans)


(n, m) = list(map(int, input().split()))
line = list(map(int, input().split()))
pairs = set()
for i in range(m):
	(a, b) = list(map(int, input().split()))
	pairs.add((a, b))
req = [line.pop()]
out = 0
while line != []:
	nex = line.pop()
	works = True
	for pers in req:
		if not (nex, pers) in pairs:
			works = False
			break
	if works:
		out += 1
	else:
		req.append(nex)
print(out)


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()]
(N, M) = RMI()
P = RMI()
G = [[] for x in range(N + 6)]
C = [0 for x in range(N + 6)]
ans = 0
for _ in range(M):
	(x, y) = RMI()
	G[y].append(x)
for i in range(N - 1, -1, -1):
	if C[P[i]] == N - 1 - i - ans and i != N - 1:
		ans += 1
	else:
		for F in G[P[i]]:
			C[F] += 1
print(ans)


(n, m) = map(int, input().split())
p = list(map(int, input().split()))
allp = set()
for i in range(m):
	(u, v) = map(int, input().split())
	allp.add((u, v))
currentList = [p.pop()]
suma = 0
while len(p) > 0:
	nextc = p.pop()
	check = True
	for i in currentList:
		if not (nextc, i) in allp:
			check = False
			break
	if check:
		suma += 1
	else:
		currentList.append(nextc)
print(suma)


import os
from io import BytesIO
input = BytesIO(os.read(0, os.fstat(0).st_size)).readline
print = lambda x: os.write(1, str(x).encode())

def main():
	(n, m) = map(int, input().split())
	p = [int(i) - 1 for i in input().split()]
	pos = p[-1]
	graph = [set() for _ in range(n)]
	for i in range(m):
		(u, v) = map(int, input().split())
		graph[u - 1].add(v - 1)
	for i in range(n - 2, -1, -1):
		while i + 1 < n and p[i + 1] in graph[p[i]]:
			(p[i], p[i + 1]) = (p[i + 1], p[i])
			i += 1
	print(n - p.index(pos) - 1)
main()


(n, m) = map(int, input().split())
l = [int(x) for x in input().split()]
pairs = [[] for i in range(n + 1)]
ans = 0
N = [0 for i in range(n + 1)]
for i in range(m):
	(a, b) = map(int, input().split())
	pairs[b].append(a)
for i in range(n - 1, -1, -1):
	if N[l[i]] == n - 1 - i - ans and i != n - 1:
		ans += 1
	else:
		for I in pairs[l[i]]:
			N[I] += 1
print(ans)


(_, m) = list(map(int, input().split()))
q = list(map(int, input().split()))
aggrement = set()
for i in range(m):
	(u, v) = list(map(int, input().split()))
	aggrement.add((u, v))
pendings = [q.pop()]
count = 0
while q != []:
	u = q.pop()
	works = True
	for pending in pendings:
		if not (u, pending) in aggrement:
			works = False
			break
	if works:
		count += 1
	else:
		pendings.append(u)
print(count)


import sys
import math as mt
input = sys.stdin.buffer.readline
t = 1
for _ in range(t):
	(n, m) = map(int, input().split())
	l = list(map(int, input().split()))
	d = {}
	for i in range(1, n + 1):
		d[i] = []
	pos = {}
	for i in range(n):
		pos[l[i]] = i
	for ____ in range(m):
		(u, v) = map(int, input().split())
		d[u].append(v)
	p = []
	d1 = [0] * (n + 1)
	for i in range(n):
		d1[l[0]] = 0
	d1[l[n - 1]] = 1
	pres = 1
	ans = 0
	for i in range(n - 2, -1, -1):
		cnt = 0
		for j in range(len(d[l[i]])):
			if d1[d[l[i]][j]] == 1:
				cnt += 1
		if cnt == pres:
			ans += 1
		else:
			pres += 1
			d1[l[i]] = 1
	print(ans)


import sys
input = sys.stdin.buffer.readline
from collections import defaultdict
(n, m) = map(int, input().split())
arr = list(map(int, input().split()))
d = defaultdict(set)
for i in range(m):
	(a, b) = map(int, input().split())
	d[a].add(b)
curr = set()
ans = 0
for i in range(n - 2, -1, -1):
	if arr[-1] in d[arr[i]]:
		if len(curr) > len(d[arr[i]]):
			curr.add(arr[i])
			continue
		flag = 0
		for j in curr:
			if j not in d[arr[i]]:
				flag = 1
				break
		if flag == 1:
			curr.add(arr[i])
		else:
			ans += 1
	else:
		curr.add(arr[i])
print(ans)


import io
import os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
(n, m) = map(int, input().split())
tmp = map(lambda x: int(x) - 1, input().split())
(ls, pointer) = ([0] * n, [0] * n)
for (i, l) in enumerate(tmp):
	ls[i] = l
	pointer[l] = i
options = [0] * n
dependencies = [[] for i in range(n)]
for _ in range(m):
	(i, j) = map(lambda x: int(x) - 1, input().split())
	if pointer[i] < pointer[j]:
		dependencies[j].append(i)
		options[i] += 1
important = n - 1
for i in range(n - 2, -1, -1):
	val = ls[i]
	nrskip = options[val]
	if important == i + nrskip:
		for d in dependencies[val]:
			options[d] -= 1
		important -= 1
print(n - important - 1)


import os
from io import BytesIO
input = BytesIO(os.read(0, os.fstat(0).st_size)).readline
ii = lambda : int(input())
mi = lambda : map(int, input().split())
li = lambda : list(mi())
(n, m) = mi()
a = li()
pairs = [li() for _ in range(m)]
last = a.pop()
friend = [[] for i in range(n + 1)]
for (u, v) in pairs:
	friend[u].append(v)
mark = [0] * (n + 1)
mark[last] = 1
req = 1
ans = 0
for i in range(n - 2, -1, -1):
	u = a[i]
	cnt = sum((mark[v] for v in friend[u]))
	if cnt == req:
		ans += 1
	else:
		mark[u] = 1
		req += 1
print(ans)


import math
from collections import deque, defaultdict
from sys import stdin, stdout
input = stdin.readline
listin = lambda : list(map(int, input().split()))
mapin = lambda : map(int, input().split())
(n, m) = mapin()
a = listin()
s = set([])
for _ in range(m):
	s.add(tuple(mapin()))
z = [a.pop()]
count = 0
while a:
	last = a.pop()
	flag = True
	for i in z:
		if (last, i) not in s:
			flag = False
			break
	if flag:
		count += 1
	else:
		z.append(last)
print(count)