class SegmentTree(): """UnitXは単位元、fは区間で行いたい操作、initは自然数あるいは配列""" def __init__(self, init, unitX, f): self.f = f # (X, X) -> X self.unitX = unitX self.f = f if type(init) == int: self.n = init self.n = 1 << (self.n - 1).bit_length() self.X = [unitX] * (self.n * 2) else: self.n = len(init) self.n = 1 << (self.n - 1).bit_length() # len(init)が2の累乗ではない時UnitXで埋める self.X = [unitX] * self.n + init + [unitX] * (self.n - len(init)) # 配列のindex1まで埋める for i in range(self.n-1, 0, -1): self.X[i] = self.f(self.X[i*2], self.X[i*2|1]) def update(self, i, x): """0-indexedのi番目の値をxで置換""" # 最下段に移動 i += self.n self.X[i] = x # 上向に更新 i >>= 1 while i: self.X[i] = self.f(self.X[i*2], self.X[i*2|1]) i >>= 1 def getvalue(self, i): """元の配列のindexの値を見る""" return self.X[i + self.n] def getrange(self, l, r): """区間[l, r)でのfを行った値""" l += self.n r += self.n al = self.unitX ar = self.unitX while l < r: # 左端が右子ノードであれば if l & 1: al = self.f(al, self.X[l]) l += 1 # 右端が右子ノードであれば if r & 1: r -= 1 ar = self.f(self.X[r], ar) l >>= 1 r >>= 1 return self.f(al, ar) import sys input = sys.stdin.readline from heapq import heappop, heappush N = int(input()) A = list(map(int, input().split())) B = list(map(int, input().split())) c = [[i,B[i]] for i in range(N)] c.sort(key = lambda x:(x[1],-x[0])) d = {c[i][0]:i for i in range(N)} st1 = SegmentTree(N+3,-10**12,max) st2 = SegmentTree(N+3,-10**12,max) res,l,r = 0,0,0 seen = set() while l1 and r not in seen: res += r-l-1 seen.add(r) else: break id = d[l] st1.update(id,-10**12) st2.update(id,-10**12) l += 1 print(res)