import std.stdio, std.array, std.string, std.conv, std.algorithm;
import std.typecons, std.range, std.random, std.math, std.container;
import std.numeric, std.bigint, core.bitop, std.bitmanip;

void main() {
    auto N = readln.chomp.to!int;
    auto C = readln.split.map!(to!long).array;
    auto A = readln.split.map!(x => x.to!int-1).array;
    auto used = new int[](N);
    int cnt = 0;
    long ans = 0;

    foreach (i; 0..N) {
        if (used[i]) continue;
        ++cnt;
        int[] nodes;
        int n = i;
        while (!used[n]) {
            nodes ~= n;
            used[n] = cnt;
            n = A[n];
        }
        if (used[n] != cnt) continue;
        bool flag = false;
        long tmp = 1L << 59;
        foreach (j; nodes) {
            if (j == n) flag = true;
            if (flag) tmp = min(tmp, C[j]);
        }

        ans += tmp;
    }

    ans.writeln;
}
