Medicine faculty of Berland State University has just finished their admission campaign. As usual, about $80\%$ of applicants are girls and majority of them are going to live in the university dormitory for the next $4$ (hopefully) years.

The dormitory consists of $n$ rooms and a single mouse! Girls decided to set mouse traps in some rooms to get rid of the horrible monster. Setting a trap in room number $i$ costs $c_i$ burles. Rooms are numbered from $1$ to $n$.

Mouse doesn't sit in place all the time, it constantly runs. If it is in room $i$ in second $t$ then it will run to room $a_i$ in second $t + 1$ without visiting any other rooms inbetween ($i = a_i$ means that mouse won't leave room $i$). It's second $0$ in the start. If the mouse is in some room with a mouse trap in it, then the mouse get caught into this trap.

That would have been so easy if the girls actually knew where the mouse at. Unfortunately, that's not the case, mouse can be in any room from $1$ to $n$ at second $0$.

What it the minimal total amount of burles girls can spend to set the traps in order to guarantee that the mouse will eventually be caught no matter the room it started from?


-----Input-----

The first line contains as single integers $n$ ($1 \le n \le 2 \cdot 10^5$) — the number of rooms in the dormitory.

The second line contains $n$ integers $c_1, c_2, \dots, c_n$ ($1 \le c_i \le 10^4$) — $c_i$ is the cost of setting the trap in room number $i$.

The third line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le n$) — $a_i$ is the room the mouse will run to the next second after being in room $i$.


-----Output-----

Print a single integer — the minimal total amount of burles girls can spend to set the traps in order to guarantee that the mouse will eventually be caught no matter the room it started from.


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

Output
3

Input
4
1 10 2 10
2 4 2 2

Output
10

Input
7
1 1 1 1 1 1 1
2 2 2 3 6 7 6

Output
2



-----Note-----

In the first example it is enough to set mouse trap in rooms $1$ and $4$. If mouse starts in room $1$ then it gets caught immideately. If mouse starts in any other room then it eventually comes to room $4$.

In the second example it is enough to set mouse trap in room $2$. If mouse starts in room $2$ then it gets caught immideately. If mouse starts in any other room then it runs to room $2$ in second $1$.

Here are the paths of the mouse from different starts from the third example:

  $1 \rightarrow 2 \rightarrow 2 \rightarrow \dots$;  $2 \rightarrow 2 \rightarrow \dots$;  $3 \rightarrow 2 \rightarrow 2 \rightarrow \dots$;  $4 \rightarrow 3 \rightarrow 2 \rightarrow 2 \rightarrow \dots$;  $5 \rightarrow 6 \rightarrow 7 \rightarrow 6 \rightarrow \dots$;  $6 \rightarrow 7 \rightarrow 6 \rightarrow \dots$;  $7 \rightarrow 6 \rightarrow 7 \rightarrow \dots$; 

So it's enough to set traps in rooms $2$ and $6$.

Difficulty: interview

Starter code:

Solutions:
import sys

rd = lambda : sys.stdin.readline().rstrip()

n = int(rd())
c = list(map(int, rd().split()))
a = list([int(x)-1 for x in rd().split()])

visited = [-1] * (n)
res = 0

for i in range(n):
    trace = []
    
    t = i
    mn = 1e9
    while visited[t] == -1:
        visited[t] = i
        trace.append(t)
        t = a[t]
        
    if visited[t] != i:
        continue
        
    while len(trace) > 0:
        v = trace.pop()
        mn = min(mn, c[v]) 
        
        if t == v: break
    
    res += mn
    
print(res)


input()
c = list(map(int, input().split()))
a = list(map(int, input().split()))

u = [0] * len(a)

ans = 0

for i in range(len(a)):
    if u[i] != 0:
        continue
    idx = i
    while u[idx] == 0:
        u[idx] = 1
        idx = a[idx] - 1
    
    if (u[idx] == 2):
        idx = i
        while u[idx] == 1:
            u[idx] = 2
            idx = a[idx] - 1
        continue

    start = idx
    mn = c[idx]
    u[idx] = 2
    while a[idx] - 1 != start:
        idx = a[idx] - 1
        mn = min(mn, c[idx])
        u[idx] = 2

    idx = i
    while u[idx] == 1:
        u[idx] = 2
        idx = a[idx] - 1
    ans += mn
print(ans)


input()
c = list(map(int, input().split()))
a = list(map(int, input().split()))

u = [0] * len(a)

ans = 0

for i in range(len(a)):
    if u[i] != 0:
        continue
    idx = i
    while u[idx] == 0:
        u[idx] = 1
        idx = a[idx] - 1
    
    if (u[idx] == 2):
        idx = i
        while u[idx] == 1:
            u[idx] = 2
            idx = a[idx] - 1
        continue

    start = idx
    mn = c[idx]
    u[idx] = 2
    while a[idx] - 1 != start:
        idx = a[idx] - 1
        mn = min(mn, c[idx])
        u[idx] = 2

    idx = i
    while u[idx] == 1:
        u[idx] = 2
        idx = a[idx] - 1
    ans += mn
print(ans)

n = int(input())
c = [0] + [int(j) for j in input().split()]
a = [0] + [int(j) for j in input().split()]
vis = [0] * (n + 1)
ans = 0
for i in range(1, n + 1):
    x = i
    while vis[x] == 0:
        vis[x] = i
        x = a[x]
    if vis[x] != i:
        continue
    v = x
    mn = c[x]
    while a[x] != v:
        x = a[x]
        mn = min(mn, c[x])
    ans += mn
print(ans)


n = int(input())
c  = [0] + [int(j) for j in input().split()]
a  = [0] + [int(j) for j in input().split()]

vis = [0] * (n+1)
ans = 0
for i in range(1,n+1):
    x = i
    while vis[x] == 0:
        vis[x] = i
        x = a[x]
    if vis[x] != i:
        continue
    v = x
    mn = c[x]
    while a[x] != v:
        x = a[x]
        mn = min(mn,c[x])
    ans+=mn
print(ans)


n = int(input())
C = [int(s) for s in input().split(" ")]
A = [int(s)-1 for s in input().split(" ")]
al = [False for i in range(0, n)]
ans = 0
for v in range(0, n):
    if al[v]:
        continue
    sequence = []
    while not al[v]:
        sequence.append(v)
        al[v] = True
        v = A[v]
    if v in sequence:
        tek = C[v]
        for j in sequence[sequence.index(v)+1:]:
            tek = min(C[j], tek)
        ans += tek
print(ans)

n=int(input())
cst=list(map(int,input().split()))
route=list(map(int,input().split()))
visited=[0]*n
cost=0
for i in range(n):
	if visited[i]==0:
		mini=99999999
		j=i
		while(visited[j]==0):
			visited[j]=i+1
			j=route[j]-1
			#print(visited,j)
			if visited[j]==i+1:
				mini=cst[j]
				k=route[j]-1
				while(k!=j):
					#print(k,j)
					if cst[k]<mini:
						mini=cst[k]
					k=route[k]-1
		if mini!=99999999:
			cost+=mini
print(cost)


n = int(input())
c = list(map(int, input().split()))
a = list([int(x) - 1 for x in input().split()])
b = [None] * n
processed = [False for i in range(n)]
for i in range(n):
    if not b[a[i]]:
        b[a[i]] = {i}
    else:
        b[a[i]].add(i)

rings = []


def processed_ring(ring):
    copy_ring = ring.copy()
    while copy_ring:
        new_ring = set()
        for el in copy_ring:
            processed[el] = True
            if b[el]:
                new_ring |= b[el]
        copy_ring = new_ring - copy_ring


for i in range(n):
    if processed[i]:
        continue
    ring = set()
    position = set()
    next_pos = i
    while next_pos not in position:
        position.add(next_pos)
        next_pos = a[next_pos]
    while next_pos not in ring:
        ring.add(next_pos)
        next_pos = a[next_pos]
    processed_ring(ring)
    rings.append(ring)

res = sum(min(c[i] for i in ring) for ring in rings)
print(res)


def main():
        n=int(input())
        c=[int(i) for i in input().split()]
        a=[int(i) for i in input().split()]
        vis=[0]*(n+1)
        sum=0
        for i in range(1,n+1):
                x=i
                while(vis[x]==0):
                        vis[x]=i
                        x=a[x-1]
                if vis[x]!=i:
                        continue
                p=x
                cos=c[x-1]
                while(p!=a[x-1]):
                        x=a[x-1]
                        cos=min(c[x-1],cos)
                sum=sum+cos
        return sum
print(main())


def count(n,c,a):
        vis=[0]*(n+1)
        z=[]
        p=[]
        for i in range(1,n+1):
                x=i
                while vis[x]==0:
                        vis[x]=i
                        x=a[x-1]
                if vis[x]==i:
                        p.append(x)
        return p
def opium(n,c,a):
        sum=0
        p=list(set(count(n,c,a)))
        #print(p)
        for x in p:
                v=x
                cd=c[x-1]
                while v!=a[x-1]:
                        x=a[x-1]
                        cd=min(cd,c[x-1])
                sum=sum+cd
                #print(sum)
        return sum
def main():
        n=int(input())
        c=[int(i) for i in input().split()]
        a=[int(i) for i in input().split()]
        return opium(n,c,a)
print(main())


n = int(input())
c  = [0] + [int(j) for j in input().split()]
a  = [0] + [int(j) for j in input().split()]
 
vis = [0] * (n+1)
ans = 0
for i in range(1,n+1):
    x = i
    while vis[x] == 0:
        vis[x] = i
        x = a[x]
    if vis[x] != i:
        continue
    v = x
    mn = c[x]
    while a[x] != v:
        x = a[x]
        mn = min(mn,c[x])
    ans+=mn
print(ans)

def main():
    n, r = int(input()) + 1, 0
    cc = [0, *list(map(int, input().split()))]
    aa = [0, *list(map(int, input().split()))]
    avail = [True] * n
    for i, a in enumerate(avail):
        if a:
            j = i
            while avail[j]:
                avail[j] = False
                j = aa[j]
            c, j = cc[j], aa[j]
            if c:
                while cc[j]:
                    if c > cc[j]:
                        c = cc[j]
                    cc[j] = 0
                    j = aa[j]
                r += c
            while cc[i]:
                cc[i] = 0
                i = aa[i]
    print(r)


def __starting_point():
    main()

__starting_point()

# -------------------------SOLVE STACK OVERFFLOW WHILE DFS
# input
n = input()
a = list(map(int, input().split())) # costs of each room
a_next = list(map(int, input().split())) # a_next[i] : the next room of ith room
for i in range(len(a_next)):
    a_next[i] -= 1
    
cycles = [] # list of cycles
check = [0]*len(a) # check array (0:unchecked, 1:visited, 2:belongs to a cycle)

# dfs function. make cycles along the way
def dfs(v):
    path = [] # path of dfs
    s = [] # dfs stack
    
    check[v] = 1
    path.append(v)
    s.append(v)

    while s:
        next_v = a_next[s[-1]]
        
        if check[next_v] == 0:
            check[next_v] = 1
            path.append(next_v)
            s.append(next_v)
        else:
            if check[next_v] == 1: # a new cycle has been found
                cycle = []
                while path[-1] != next_v:
                    cycle.append(path.pop())
                cycle.append(next_v)
                cycles.append(cycle)
            # empty the stack
            while s:
                check[s.pop()] = 2

# make a list of cycles
for i in range(len(a)):
    if check[i] == 0:
        dfs(i)

# add up all minimum costs for each cycle
ans = 0 # answer
for cycle in cycles:
    min_cost = a[cycle[0]]
    for v in cycle:
        if a[v] < min_cost:
            min_cost = a[v]
    ans += min_cost

# print answer
print(ans)


n = int(input())

c = list(map(int, input().split()))

a = list([int(x) - 1 for x in input().split()])

deg_in = [0 for _ in range(n)]

d_in_to_v_set = {i: set() for i in range(n + 1)}

for ai in a:
    deg_in[ai] += 1

for i in range(n):
    d_in_to_v_set[deg_in[i]].add(i)

while d_in_to_v_set[0] != set():
    l = list(d_in_to_v_set[0])
    for u in l:
        d_in_to_v_set[deg_in[a[u]]].remove(a[u])
        d_in_to_v_set[deg_in[a[u]] - 1].add(a[u])
        d_in_to_v_set[0].remove(u)
        deg_in[a[u]] -= 1

p = [0 for _ in range(n)]

for v in d_in_to_v_set[1]:
    p[v] = 1

ans, cur = 0, 10**5

for i in range(n):
    s = i
    cur = 10**5
    while p[s] != 0:
        cur = min(cur, c[s])
        p[s] = 0
        s = a[s]
    ans += cur if cur < 10**5 else 0

print(ans)


n = int(input())

c = list(map(int, input().split()))

a = list([int(x) - 1 for x in input().split()])

deg_in = [0 for _ in range(n)]

d_in_to_v_set = {i: set() for i in range(n + 1)}

for ai in a:
    deg_in[ai] += 1

for i in range(n):
    d_in_to_v_set[deg_in[i]].add(i)

while d_in_to_v_set[0] != set():
    l = list(d_in_to_v_set[0])
    for u in l:
        d_in_to_v_set[deg_in[a[u]]].remove(a[u])
        d_in_to_v_set[deg_in[a[u]] - 1].add(a[u])
        d_in_to_v_set[0].remove(u)
        deg_in[a[u]] -= 1

p = [0 for _ in range(n)]

for v in d_in_to_v_set[1]:
    p[v] = 1

ans, cur = 0, 10**5

for i in range(n):
    s = i
    cur = 10**5
    while p[s] != 0:
        cur = min(cur, c[s])
        p[s] = 0
        s = a[s]
    ans += cur if cur < 10**5 else 0

print(ans)


# -*- coding:utf-8 -*-

"""

created by shuangquan.huang at 12/10/18

"""

N = int(input())
C = [0] + [int(x) for x in input().split()]
A = [0] + [int(x) for x in input().split()]


ans = 0
vis = [False] * (N+1)
for i in range(1, N+1):
    if vis[i]:
        continue
    
    circle = []
    u = i
    while not vis[u]:
        circle.append(u)
        vis[u] = True
        u = A[u]
    
    if u in circle:
        ans += min([C[j] for j in circle[circle.index(u):]])

print(ans)

n = int(input())
c = [0] + list(map(int, input().split()))
a = [0] + list(map(int, input().split()))

g = [0] * (n+1)
answer = 0

for i in range(1,n+1):
    node = i
    while g[node] == 0:
        g[node] = i
        node = a[node]
    if g[node] != i:
        continue
    current = node
    min_cost = c[node]
    while a[node] != current:
        node = a[node]
        min_cost = min(min_cost,c[node])
    answer += min_cost

print(answer)

# n = input()
# a = input()
# b = input()
# print(n)
# print(a)
# print(b)
# import sys
# sys.setrecursionlimit(1000000)
# try:
n = int(input())
burles = list(map(int, input().split()))
directions = list(map(int, input().split()))

burles.insert(0,0)
directions.insert(0,0)


v = [0]*(n+1)# visitou
g = [0]*(n+1)# grupo



def passa(pos):

	nonlocal current_group
	nonlocal v
	nonlocal g
	nonlocal soma_total
	pilha = [-1]
	avanco = True
	# print('posicao {} {}'.format(pos, v[pos]))
	# print('Visita {}'.format(pos))
	grupo = 0
	esta_no_ciclo = False
	menor_local = 0
	while pilha:
		
		if avanco:

			if v[pos] == 1:
				v[pos] = 2
				if g[pos] == 0:
					g[pos] = current_group
					# print('atribui grupo {}'.format(current_group))
					current_group+=1
				
				grupo = g[pos]
				avanco = False
				esta_no_ciclo = True
				menor_local = burles[pos]

			elif v[pos] == 2 or v[pos] == 3:
				grupo = g[pos]
				avanco = False
				esta_no_ciclo = False
				grupo = g[pos]
			else:	
				v[pos] = 1
				pilha.append(pos)
				pos = directions[pos]
		
		# g[pos], ver, minimo = passa(directions[pos])
		
		else:
			pos = pilha.pop(len(pilha)-1)
			if pos < 0:
				continue
			g[pos] = grupo
			if v[pos] ==2 and esta_no_ciclo:
				soma_total+=menor_local
				esta_no_ciclo = False

				# return g[pos], False, 0

			elif v[pos] ==1 and esta_no_ciclo:
				v[pos] = 2
				menor_local = min(menor_local, burles[pos])
				# return g[pos], True, min(minimo, burles[pos])
			
			if v[pos] ==1 and not esta_no_ciclo:
				v[pos] = 3

				# return g[pos], False, 0


			# return g[pos], False, 0
	# print('atribui grupo {}'.format(g[pos]))

current_group = 1
soma_total = 0
for i in range(1, n+1):
	if v[i] ==0:
		passa(i)
print(soma_total)
# except Exception:
# print(sys.exc_info()[2])



# dicionario = {}
# for i in range(1, n+1):
# 	if v[i] == 2:
# 		grupo = g[i]
# 		menor = dicionario.get(grupo, None)
# 		if menor:
# 			dicionario[grupo] = min(menor, burles[i])

# 		else:
# 			dicionario[grupo] = burles[i]

# print(int(sum(dicionario.values())))

# except RuntimeError as e:
# 	print(1)
# 	print(str(e))

# print(g)
# print(v)

# conjunto = set()
# soma = 0
# for i in range(1, len(p)):
# 	if g[i] not in conjunto:
# 		conjunto.add(g[i])
# 		soma+=p[i]



# answer = 0

# for i in range(1,n+1):
#     node = i
#     while g[node] == 0:
#         g[node] = i
#         node = a[node]
#     if g[node] != i:
#         continue
#     current = node
#     min_cost = c[node]
#     while a[node] != current:
#         node = a[node]
#         min_cost = min(min_cost,c[node])
#     answer += min_cost

# print(answer)
# print(v)
# print(g)
# print(p)
# print(dicionario)


# n = input()
# a = input()
# b = input()
# print(n)
# print(a)
# print(b)
# import sys
# sys.setrecursionlimit(1000000)
# try:
n = int(input())
burles = list(map(int, input().split()))
directions = list(map(int, input().split()))

burles.insert(0,0)
directions.insert(0,0)


v = [0]*(n+1)# visitou
g = [0]*(n+1)# grupo



def passa(pos):

	nonlocal current_group
	nonlocal v
	nonlocal g
	nonlocal soma_total
	pilha = [-1]
	avanco = True
	# print('posicao {} {}'.format(pos, v[pos]))
	# print('Visita {}'.format(pos))
	grupo = 0
	esta_no_ciclo = False
	menor_local = 0
	while pilha:
		
		if avanco:

			if v[pos] == 1:
				v[pos] = 2
				if g[pos] == 0:
					g[pos] = current_group
					# print('atribui grupo {}'.format(current_group))
					current_group+=1
				
				grupo = g[pos]
				avanco = False
				esta_no_ciclo = True
				menor_local = burles[pos]

			elif v[pos] == 2 or v[pos] == 3:
				grupo = g[pos]
				avanco = False
				esta_no_ciclo = False
				grupo = g[pos]
			else:	
				v[pos] = 1
				pilha.append(pos)
				pos = directions[pos]
		
		# g[pos], ver, minimo = passa(directions[pos])
		
		else:
			pos = pilha.pop(len(pilha)-1)
			if pos < 0:
				continue
			g[pos] = grupo
			if v[pos] ==2 and esta_no_ciclo:
				soma_total+=menor_local
				esta_no_ciclo = False

				# return g[pos], False, 0

			elif v[pos] ==1 and esta_no_ciclo:
				v[pos] = 2
				menor_local = min(menor_local, burles[pos])
				# return g[pos], True, min(minimo, burles[pos])
			
			if v[pos] ==1 and not esta_no_ciclo:
				v[pos] = 3

				# return g[pos], False, 0


			# return g[pos], False, 0
	# print('atribui grupo {}'.format(g[pos]))

current_group = 1
soma_total = 0
for i in range(1, n+1):
	if v[i] ==0:
		passa(i)
print(soma_total)
# except Exception:
# print(sys.exc_info()[2])



# dicionario = {}
# for i in range(1, n+1):
# 	if v[i] == 2:
# 		grupo = g[i]
# 		menor = dicionario.get(grupo, None)
# 		if menor:
# 			dicionario[grupo] = min(menor, burles[i])

# 		else:
# 			dicionario[grupo] = burles[i]

# print(int(sum(dicionario.values())))

# except RuntimeError as e:
# 	print(1)
# 	print(str(e))

# print(g)
# print(v)

# conjunto = set()
# soma = 0
# for i in range(1, len(p)):
# 	if g[i] not in conjunto:
# 		conjunto.add(g[i])
# 		soma+=p[i]



# answer = 0

# for i in range(1,n+1):
#     node = i
#     while g[node] == 0:
#         g[node] = i
#         node = a[node]
#     if g[node] != i:
#         continue
#     current = node
#     min_cost = c[node]
#     while a[node] != current:
#         node = a[node]
#         min_cost = min(min_cost,c[node])
#     answer += min_cost

# print(answer)
# print(v)
# print(g)
# print(p)
# print(dicionario)


def dfs(node,edges,costs,visited):
    cycle = False
    visited1 = set()
    while True:
        if node in visited:
            for i in visited1:
                visited.add(i)
            return 0
        if not edges[node]:
            visited1.add(node)
            break
        if node not in visited1:
            visited1.add(node)
            node = edges[node][0]
        else:
            cycle = True
            break

    #print(node,cycle,visited)
    if cycle:
        x = edges[node][0]
        min_cost = costs[x-1]
        while x != node:
            x = edges[x][0]
            min_cost = min(min_cost,costs[x-1])
        cost = min_cost
    else:
        cost = costs[node-1]

    for i in visited1:
        visited.add(i)

    return cost
    

def solve(zero,edges,costs):
    n = len(costs)
    visited = set()
    cost = 0

    for i in range(1,n+1):
        if i not in visited:
            cost += dfs(i,edges,costs,visited)

    print(cost)

def main():
    n = int(input())
    costs = list(map(int,input().split()))
    mouse = list(map(int,input().split()))
    edges = {}
    for i in range(1,n+1):
        edges[i] = []

    indegree = [0]*(n+1)
    for i in range(1,n+1):
        if i != mouse[i-1]:
            edges[i].append(mouse[i-1])
            indegree[mouse[i-1]] += 1

    zero = []
    for i in range(1,n+1):
        if indegree[i] == 0:
            zero.append(i)

    solve(zero,edges,costs)


main()


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

ans=0
v=[False for i in range(n)]
for i in range(n):
	if v[i]:continue
	p=set()
	pl=[]
	s=set([i])
	t=True
	while s and t:
		x=s.pop()
		v[x]=True
		p.add(x)
		pl.append(x)
		nex=a[x]-1
		s.add(nex)
		if nex in p:
			j=pl.index(nex)
			za=s.pop()
		elif v[nex]:t=False;za=s.pop()
		
	
	if not t:continue
	an=float("INF")
	for k in range(j,len(pl)):
		an=min(c[pl[k]],an)
	ans+=an
print(ans)

# 1027D
import collections
def do():
    n = int(input())
    costs = [int(c) for c in input().split(" ")]
    next = [int(c)-1 for c in input().split(" ")]
    ind = [0] * n
    for i,c in enumerate(next):
        if i != c:
            ind[c] += 1
    seen = [0] * n
    res_seen = [0] * n
    res = 0

    def get(entry):
        m = costs[entry]
        p = entry
        while True:
            if res_seen[p]:
                return 0
            res_seen[p] = 1
            m = min(m, costs[p])
            p = next[p]
            if p == entry:
                break
        return m

    def dfs(i):
        stack = [i]
        seen[i] = 1
        while stack:
            cur = stack.pop()
            nei = next[cur]
            if seen[nei]:
                return get(nei)
            seen[nei] = 1
            stack.append(nei)
        return 0

    for i in range(n):
        if ind[i] == 0:
            res += dfs(i)
    for i in range(n):
        if seen[i] == 0:
            res += dfs(i)
    return res

print(do())


import sys
readline = sys.stdin.readline


N = int(readline())
C = list(map(int, readline().split()))
A = list(map(lambda x: int(x)-1, readline().split()))


inf = 10**9
used = set()
ans = 0
for i in range(N):
    if i in used:
        continue
    seen = set()
    stack = [i]
    cnt = 0
    st = None
    while stack:
        vn = stack.pop()
        vf = A[vn]
        if vf in used:
            break
        if vf in seen:
            st = vf
            break
        seen.add(vf)
        stack.append(vf)
        
    if st is not None:
        vn = st
        cnt = C[vn]
        vf = A[vn]
        vn = A[vn]
        while vn != st:
            cnt = min(cnt, C[vn])
            vn = A[vn]
    used |= seen
    ans += cnt
print(ans)

import sys
input = sys.stdin.readline

class Unionfind:
    def __init__(self, n):
        self.par = [-1]*n
        self.rank = [1]*n
    
    def root(self, x):
        p = x
        
        while not self.par[p]<0:
            p = self.par[p]
        
        while x!=p:
            tmp = x
            x = self.par[x]
            self.par[tmp] = p
        
        return p
    
    def unite(self, x, y):
        rx, ry = self.root(x), self.root(y)
        
        if rx==ry: return False
        
        if self.rank[rx]<self.rank[ry]:
            rx, ry = ry, rx
        
        self.par[rx] += self.par[ry]
        self.par[ry] = rx
    
        if self.rank[rx]==self.rank[ry]:
            self.rank[rx] += 1
    
    def is_same(self, x, y):
        return self.root(x)==self.root(y)
    
    def count(self, x):
        return -self.par[self.root(x)]
        
n = int(input())
c = list(map(int, input().split()))
uf = Unionfind(n)
a = list(map(int, input().split()))

for i in range(n):
    uf.unite(i, a[i]-1)

roots = set(uf.root(i) for i in range(n))
ans = 0

for r in roots:
    cur = r
    s = {r}
    
    while True:
        nex = a[cur]-1
        
        if nex in s:
            sta = nex
            break
        
        s.add(nex)
        cur = nex
    
    add = c[sta]
    cur = sta
    
    while True:
        nex = a[cur]-1
        
        if nex==sta:
            break
        
        add = min(add, c[nex])
        cur = nex
    
    ans += add

print(ans)

n = int(input())
c = list(map(int, input().strip().split()))
a = list(map(int, input().strip().split()))
resd = {}
res = 0
tmpd = {}
for i in range(n):
    cur = i + 1
    d = {}
    group = []
    flag = False
    while cur not in d:
        if cur in tmpd:
            flag = True
            break
        d[cur] = 1
        tmpd[cur] = 1
        group.append(cur)
        cur = a[cur - 1]
    if flag:
        continue
    mmin = float('inf')
    ind = float('inf')
    flag = False
    for item in group:
        if item == cur:
            flag = True
        if flag:
            mmin = min(c[item - 1], mmin)
            ind = min(ind, item)
    if ind in resd:
        continue
    else:
        resd[ind] = 1
        res += mmin

print(res)