#!/usr/bin/ python3.8 import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines from scipy.sparse.csgraph import connected_components import numpy as np N = int(readline()) LS = np.array(read().split(), np.int32) L = LS[::2] S = LS[1::2] - 1 graph = np.zeros((N, N), np.bool) graph[np.arange(N), S] = 1 Ncomp, comp = connected_components(graph, connection='strong') out_deg = [0] * Ncomp for i, s in enumerate(S): ci = comp[i] cs = comp[s] if ci == cs: continue out_deg[ci] += 1 answer = 0 for i in range(Ncomp): V = np.where(comp == i)[0] x = L[V].sum() y = L[V].min() if out_deg[i] == 0: x += y answer += x print(answer / 2)