Consider a tunnel on a one-way road. During a particular day, $n$ cars numbered from $1$ to $n$ entered and exited the tunnel exactly once. All the cars passed through the tunnel at constant speeds.

A traffic enforcement camera is mounted at the tunnel entrance. Another traffic enforcement camera is mounted at the tunnel exit. Perfectly balanced.

Thanks to the cameras, the order in which the cars entered and exited the tunnel is known. No two cars entered or exited at the same time.

Traffic regulations prohibit overtaking inside the tunnel. If car $i$ overtakes any other car $j$ inside the tunnel, car $i$ must be fined. However, each car can be fined at most once.

Formally, let's say that car $i$ definitely overtook car $j$ if car $i$ entered the tunnel later than car $j$ and exited the tunnel earlier than car $j$. Then, car $i$ must be fined if and only if it definitely overtook at least one other car.

Find the number of cars that must be fined. 


-----Input-----

The first line contains a single integer $n$ ($2 \le n \le 10^5$), denoting the number of cars.

The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le n$), denoting the ids of cars in order of entering the tunnel. All $a_i$ are pairwise distinct.

The third line contains $n$ integers $b_1, b_2, \ldots, b_n$ ($1 \le b_i \le n$), denoting the ids of cars in order of exiting the tunnel. All $b_i$ are pairwise distinct.


-----Output-----

Output the number of cars to be fined.


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

Output
2

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

Output
6

Input
2
1 2
1 2

Output
0



-----Note-----

The first example is depicted below:

[Image]

Car $2$ definitely overtook car $5$, while car $4$ definitely overtook cars $1$, $2$, $3$ and $5$. Cars $2$ and $4$ must be fined.

In the second example car $5$ was definitely overtaken by all other cars.

In the third example no car must be fined.

Difficulty: interview

Starter code:

Solutions:
n=int(input())
l1=list(map(int,input().split()))
l2=list(map(int,input().split()))
fined=0
i=0
j=0
d1={}
while i<n and j<n:
    if l1[i] in d1:
        i+=1
        continue
    if l1[i]==l2[j]:
        i+=1
        j+=1
    else :
        while j<n and l2[j]!=l1[i]:
            d1[l2[j]]=1
            j+=1
            fined+=1
print(fined)

n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))

i = 0
j = 0
ans = 0
s = set()
while i < len(a):
    if a[i] in s:
        i += 1
        continue
    while b[j] != a[i]:
        s.add(b[j])
        ans += 1
        j += 1
    i += 1
    j += 1
print(ans)


n = int(input())

arr1 = list(map(int, input().split(' ')))
arr2 = list(map(int, input().split(' ')))

excluded = [False] * (n + 1)
sol = 0

i = 0
j = 0

while(i < n and j < n):
  if(excluded[arr1[i]]):
    i += 1
    continue

  if(arr1[i] == arr2[j]):
    i += 1
    j += 1
  else:
    excluded[arr2[j]] = True
    j += 1
    sol += 1
  
print(sol)


n=int(input())
it=list(map(int,input().split()))
aa=list(map(int,input().split()))
ss={}
for i in range(n):
    ss[it[i]]=i
aa=[ss[i] for i in aa]
ma=n+1
tot=0
d=[0]*n
mi=0
for i in range(n):
    if aa[i]>mi:
        tot+=1
    d[aa[i]]=1
    
    if mi==aa[i]:
        while mi<n:
            if d[mi]==1:
                mi+=1
            else:
                break
        
print(tot)


n = int(input())
l1 = list(map(int,input().split()))
l2 = list(map(int,input().split()))
l1.reverse()
l2.reverse()
trans = [0] * n
for i in range(n):
	trans[l1[i] - 1] = i
end = [0] * n
for i in range(n):
	end[i] = trans[l2[i] - 1]
wyn = 0
maksi = end[0]
for i in range(1, n):
	if end[i] < maksi:
		wyn += 1
	maksi = max(end[i], maksi)
print(wyn)

n = int(input())
a = list(map(int, input().split()))
d = [0]*n
for q in range(len(a)):
    d[a[q]-1] = q
s = list(map(int, input().split()))
for q in range(len(s)):
    s[q] = d[s[q]-1]
f = [0]*n
ans = q1 = 0
for q in range(len(s)):
    f[s[q]] = 1
    if s[q] == q1:
        while q1 < len(f) and f[q1]:
            q1 += 1
    if s[q] > q1:
        ans += 1
print(ans)


n=int(input())
d=dict()
l=[int(j) for j in input().split()]
l2=[int(j) for j in input().split()]
f=0
c=0
for i in range(n):
    t=l[i]
    if f==n:
        break
    if not(t in d):
        while l2[c]!=t and c<n:
            k=l2[c]
        
            if not(k in d):
                d[k]=1
                f+=1
            c+=1
        c+=1
print(f)


import sys
input = lambda: sys.stdin.readline().rstrip()

N = int(input())
A = [int(a)-1 for a in input().split()][::-1]

C = [-1] * N
for i in range(N):
    C[A[i]] = i

B = [C[int(a)-1] for a in input().split()][::-1]

ans, ma = 0, -1
for i in B:
    if ma > i:
        ans += 1
    ma = max(ma, i)
print(ans)




n=int(input())
arr=list(map(int,input().split()))
brr=list(map(int,input().split()))
prev=-1
d=dict()
for i in range(n):
    d[brr[i]]=i
ans=0
for i in range(n):
    if(d[arr[i]]-prev>0):
        ans+=(d[arr[i]]-prev-1)
        prev=d[arr[i]]
        
print(ans)
        


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


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


def num ():
	return map (int, sys.stdin.readline ().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)

mm = 1000000007
fact_powers=[0]*19
tset=set()

def go ( ind, x ):
	if (ind == 19):
		tset.add (x)
		return

	if (x in tset):
		return
	go (ind + 1, x)
	i = 0
	for xx in fact_powers [ ind ]:
		p = x * xx
		if (p >1e18):
			break
		go (ind + 1, p)

def solve ():
	t = 1
	for tt in range (t):
		n=nu()
		a=li()
		b=li()
		i=0
		j=0
		s=set()
		cc=0
		while(i<n and j<n):
			if(a[i]==b[j]):
				i+=1
				j+=1
			else:
				if(a[i]in s):
					i+=1
					continue
				s.add(b[j])
				cc+=1
				j+=1
		print(cc)







def __starting_point():
	solve ()
__starting_point()

import sys
input = sys.stdin.readline

n=int(input())
A=list(map(int,input().split()))
B=list(map(int,input().split()))

inda=0
indb=0
ANS=0
USE=[0]*(n+1)

while inda<n and indb<n:
    NOW=A[inda]
    USE[A[inda]]=1

    for i in range(indb,n):
        if B[i]==NOW:
            break
        else:
            if USE[B[i]]==0:
                ANS+=1
                USE[B[i]]=1

    indb=i+1
    
    while inda<n and USE[A[inda]]==1:
        inda+=1

    #print(inda,indb,ANS)

print(ANS)


''' CODED WITH LOVE BY SATYAM KUMAR '''

from sys import stdin, stdout
import heapq
import cProfile, math
from collections import Counter, defaultdict, deque
from bisect import bisect_left, bisect, bisect_right
import itertools
from copy import deepcopy
from fractions import Fraction
import sys, threading
import operator as op
from functools import reduce
import sys

sys.setrecursionlimit(10 ** 6)  # max depth of recursion
threading.stack_size(2 ** 27)  # new thread will get stack of such size
fac_warm_up = False
printHeap = str()
memory_constrained = False
P = 10 ** 9 + 7


class MergeFind:
    def __init__(self, n):
        self.parent = list(range(n))
        self.size = [1] * n
        self.num_sets = n
        self.lista = [[_] for _ in range(n)]

    def find(self, a):
        to_update = []
        while a != self.parent[a]:
            to_update.append(a)
            a = self.parent[a]
        for b in to_update:
            self.parent[b] = a
        return self.parent[a]

    def merge(self, a, b):
        a = self.find(a)
        b = self.find(b)
        if a == b:
            return
        if self.size[a] < self.size[b]:
            a, b = b, a
        self.num_sets -= 1
        self.parent[b] = a
        self.size[a] += self.size[b]
        self.lista[a] += self.lista[b]

    def set_size(self, a):
        return self.size[self.find(a)]

    def __len__(self):
        return self.num_sets


def display(string_to_print):
    stdout.write(str(string_to_print) + "\n")


def prime_factors(n):  # n**0.5 complex
    factors = dict()
    for i in range(2, math.ceil(math.sqrt(n)) + 1):
        while n % i == 0:
            if i in factors:
                factors[i] += 1
            else:
                factors[i] = 1
            n = n // i
    if n > 2:
        factors[n] = 1
    return (factors)


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


def fibonacci_modP(n, MOD):
    if n < 2: return 1
    return (cached_fn(fibonacci_modP, (n + 1) // 2, MOD) * cached_fn(fibonacci_modP, n // 2, MOD) + cached_fn(
        fibonacci_modP, (n - 1) // 2, MOD) * cached_fn(fibonacci_modP, (n - 2) // 2, MOD)) % MOD


def factorial_modP_Wilson(n, p):
    if (p <= n):
        return 0
    res = (p - 1)
    for i in range(n + 1, p):
        res = (res * cached_fn(InverseEuler, i, p)) % p
    return res


def binary(n, digits=20):
    b = bin(n)[2:]
    b = '0' * (digits - len(b)) + b
    return b


def is_prime(n):
    """Returns True if n is prime."""
    if n < 4:
        return True
    if n % 2 == 0:
        return False
    if n % 3 == 0:
        return False
    i = 5
    w = 2
    while i * i <= n:
        if n % i == 0:
            return False
        i += w
        w = 6 - w
    return True


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


factorial_modP = []


def warm_up_fac(MOD):
    nonlocal factorial_modP, fac_warm_up
    if fac_warm_up: return
    factorial_modP = [1 for _ in range(fac_warm_up_size + 1)]
    for i in range(2, fac_warm_up_size):
        factorial_modP[i] = (factorial_modP[i - 1] * i) % MOD
    fac_warm_up = True


def InverseEuler(n, MOD):
    return pow(n, MOD - 2, MOD)


def nCr(n, r, MOD):
    nonlocal fac_warm_up, factorial_modP
    if not fac_warm_up:
        warm_up_fac(MOD)
        fac_warm_up = True
    return (factorial_modP[n] * (
            (pow(factorial_modP[r], MOD - 2, MOD) * pow(factorial_modP[n - r], MOD - 2, MOD)) % MOD)) % MOD


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


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


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


memory = dict()


def clear_cache():
    nonlocal memory
    memory = dict()


def cached_fn(fn, *args):
    nonlocal memory
    if args in memory:
        return memory[args]
    else:
        result = fn(*args)
        memory[args] = result
        return result


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


def binary_search(i, li):
    fn = lambda x: li[x] - x // i
    x = -1
    b = len(li)
    while b >= 1:
        while b + x < len(li) and fn(b + x) > 0:  # Change this condition 2 to whatever you like
            x += b
        b = b // 2
    return x


# -------------------------------------------------------------- MAIN PROGRAM


TestCases = False
optimise_for_recursion = True  # Can not be used clubbed with TestCases WHen using recursive functions, use Python 3


def main():
    n = get_int()
    ai = get_list()
    bi = get_list()
    bi.reverse()
    ai.reverse()
    pos = 0
    fined = set()
    for ele in ai:
        while pos<n and bi[pos] in fined:
            pos += 1
        if ele==bi[pos]:
            pos+=1
        else:
            fined.add(ele)
    print(len(fined))








# --------------------------------------------------------------------- END=


if TestCases:
    for i in range(get_int()):
        main()
else:
    main() if not optimise_for_recursion else threading.Thread(target=main).start()


import math

def main():
    n = int(input())
    a = [int(x) for x in input().split()]
    b = [int(x) for x in input().split()]

    out = set()
    j = 0
    result = 0
    for i in range(n):
        if b[i] != a[j]:
            out.add(b[i])
            result += 1
        else:
            j += 1
            while j < n and a[j] in out:
                j += 1
    print(result)




def __starting_point():
    main()

__starting_point()

#TO MAKE THE PROGRAM FAST

''' ----------------------------------------------------------------------------------------------------  '''
import sys
input = sys.stdin.readline
sys.setrecursionlimit(100000)
''' ----------------------------------------------------------------------------------------------------  '''




#FOR TAKING INPUTS

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




#MAIN PROGRAM

''' ----------------------------------------------------------------------------------------------------  '''

n = val()
l1 = li()
l2 = li()
d = {}
t = 0
for i in l1:
    d[i] = t
    t += 1

s = set()
t = 0
tot = 0
for i in l2:
    if d[i] != t:
        tot += 1
        s.add(d[i])
    else:
        t += 1
        while t in s:
            t += 1
print(tot)




''' ----------------------------------------------------------------------------------------------------  '''

ans=0
d={}
ans=0
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
i=n-1
j=n-1
d={}
while (i>=0):
    if a[i]==b[j]:
        i-=1
        j-=1
    else:
        d[a[i]]=1
        if b[j] not in d:
            i-=1
            ans+=1
        else:
            j-=1
        
print(ans)        

n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
memo = {}

for i in range(n):
    memo[a[i]] = i

ans = [0] * n
for i in range(n):
    ans[i] = memo[b[i]]

min_num = 10**9
cnt = 0

for i in range(n)[::-1]:
    if ans[i] > min_num:
        cnt += 1
    min_num = min(min_num, ans[i])
print(cnt)

n=int(input())
a=[int(x) for x in input().split()]
b=[int(x) for x in input().split()]
dic={}
arr=0
maxim=0
for i in range(n):
    dic[b[i]]=i
for item in a:
    if dic[item]<maxim:
        arr+=1
    maxim=max(maxim,dic[item])
print(arr)
    


3

import array
import math
import os
import sys


def main():
    N = read_int()
    A = read_ints()
    B = read_ints()
    print(solve(N, A, B))


def solve(N, A, B):
    T = {}
    i = 0
    for b in B:
        T[b] = i
        i += 1

    last_pos = -1
    ans = 0
    for a in A:
        t = T[a]
        if t > last_pos:
            last_pos = t
        else:
            ans += 1

    return ans


DEBUG = 'DEBUG' in os.environ


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


def read_int():
    return int(inp())


def read_ints():
    return [int(e) for e in inp().split()]


def dprint(*value, sep=' ', end='\n'):
    if DEBUG:
        print(*value, sep=sep, end=end)


def __starting_point():
    main()

__starting_point()

import bisect
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
a_dict = {}
for i in range(n):
    a_dict[a[i]] = i+1
for i in range(n):
    b[i] = a_dict[b[i]]
b.reverse()

ans = 0
mini = n
for i in range(n):
    if mini >= b[i]:
        mini = b[i]
    else:
        ans += 1

print(ans)


from heapq import heappush, heappop
from collections import deque,defaultdict,Counter
import itertools
from itertools import permutations,combinations
import sys
import bisect
import string
#import math
#import time
#import random  # randome is not available at Codeforces
def I():
    return int(input())
def MI():
    return map(int,input().split())
def LI():
    return [int(i) for i in input().split()]
def LI_():
    return [int(i)-1 for i in input().split()]
def StoI():
    return [ord(i)-97 for i in input()]
def show(*inp,end='\n'):
    if show_flg:
        print(*inp,end=end)
YN=['Yes','No']
mo=10**9+7
inf=float('inf')
#ts=time.time()
#sys.setrecursionlimit(10**6)
input=lambda: sys.stdin.readline().rstrip()
import sys
sys.setrecursionlimit(10**7)

show_flg=False
#show_flg=True


n=I()
en=LI()[::-1]
ex=LI()[::-1]

show(en,ex)
ans=0
f=[0]*(n+1)
while en:
    c=en.pop()
    if f[c]==1:
        continue
    while ex:
        d=ex.pop()
        if d==c:
            break
        ans+=1
        f[d]=1
        show(c,d,en,ex)

print(ans)

show(f)

n = int(input())
a = [*map(int, input().split())]
b = [*map(int, input().split())]
d = {e: i for i, e in enumerate(a)}
res = 0
cur = float('inf')
for e in b[::-1]:
    if d[e] > cur: 
        res += 1
    else: cur = d[e]
print(res)

n = int(input())
d = list(map(int, input().split()))
p = list(map(int, input().split()))
o = set()
i = 0
j = 0
while j < n:
    if d[i] in o:
        i += 1
    elif d[i] != p[j]:
        o.add(p[j])
        j += 1
    else:
        i += 1
        j += 1
print(len(o))

n=int(input())
a=list(map(int,input().strip().split()))
b=list(map(int,input().strip().split()))
op=[0]*(n+1)
i=0
j=0
while(i<n and j<n):
    # print(a[i],b[j])
    if(a[i]==b[j]):
        i+=1
        while(i<n and op[a[i]]==1):
            i+=1
        j+=1
    else:
        op[b[j]]=1
        j+=1
    
print(sum(op))
# print(op)



n = int(input())


a = list(map(int, input().split()))
dictt = {}
for x in range(n):
    dictt[a[x]] = x
# print(dictt)
b = list(map(int, input().split()))
bb = []
for x in b:
    bb.append(dictt[x])
# print(bb)
bb.reverse()
# work with bb
fines = 0
smallest = bb[0]
largest = bb[0]
for i in range(1, n):
    if bb[i] > smallest:
        fines += 1
        # print(f"xx{i}")
    if bb[i] > largest:
        largest = bb[i]
    if bb[i] < smallest:
        smallest = bb[i]
print(fines)