#include <bits/stdc++.h>
using namespace std;
const int maxn = 200100;
struct compass {
  int dat, nxt;
} p[maxn];
long long head[maxn], s[maxn], ha[maxn], cd[maxn], rd[maxn], tot, num, c[maxn],
    a[maxn], ans, n;
int read() {
  int tot = 0, fh = 1;
  char c = getchar();
  while (c < '0' || c > '9') {
    if (c == '-') fh = -1;
    c = getchar();
  }
  while (c >= '0' && c <= '9') {
    tot = tot * 10 + c - '0';
    c = getchar();
  }
  return tot * fh;
}
void connect(int x, int y) {
  tot++;
  p[tot].nxt = head[x];
  p[tot].dat = y;
  head[x] = tot;
}
void dfs(int x) {
  num++;
  s[num] = x;
  ha[x] = 1;
  for (int i = head[x]; i; i = p[i].nxt)
    if (ha[p[i].dat] == 1) {
      int mn = c[p[i].dat], rem = num;
      while (s[num] != p[i].dat && num > 0) num--;
      if (num != 0) {
        num++;
        while (s[num] != p[i].dat && num <= rem) {
          if (c[s[num]] < mn) mn = c[s[num]];
          num++;
        }
        ans += mn;
      }
    } else
      dfs(p[i].dat);
  if (cd[x] == 0) ans += c[x];
}
int main() {
  n = read();
  for (int i = 1; i <= n; i++) c[i] = read();
  for (int i = 1; i <= n; i++) {
    a[i] = read();
    if (a[i] == i) {
      ans += c[i];
      ha[i] = 1;
    } else {
      rd[a[i]]++;
      cd[i]++;
      connect(i, a[i]);
    }
  }
  for (int i = 1; i <= n; i++)
    if (rd[i] == 0 && a[i] != i) {
      num = 0;
      dfs(i);
    }
  for (int i = 1; i <= n; i++)
    if (ha[i] == 0 && a[i] != i) dfs(i);
  cout << ans << endl;
  return 0;
}
