#include <bits/stdc++.h>
using namespace std;
const int mod = (1e9) + 7;
const double eps = 1e-6;
const int siz = 2e5 + 5, siz2 = 1e5 + 5;
int n, c[siz], a[siz];
bool vis[siz], inst[siz];
long long tot = 0;
vector<int> st;
void dfs(int i) {
  if (inst[i]) {
    int mn = INT_MAX;
    for (int j = st.size() - 1; j >= 0; j--) {
      int v = st[j];
      mn = min(mn, c[v]);
      if (v == i) {
        break;
      }
    }
    tot += mn;
    return;
  }
  if (vis[i]) {
    return;
  }
  vis[i] = true;
  inst[i] = true;
  st.push_back(i);
  dfs(a[i]);
  inst[i] = false;
  st.pop_back();
}
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    scanf("%d", &c[i]);
  }
  for (int i = 1; i <= n; i++) {
    scanf("%d", &a[i]);
  }
  for (int i = 1; i <= n; i++) {
    dfs(i);
  }
  printf("%I64d\n", tot);
  return 0;
}
