#include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
using namespace std;
template <typename T1, typename T2>
inline void chkMin(T1 &x, T2 y) {
  if (x > y) x = y;
}
template <typename T1, typename T2>
inline void chkMax(T1 &x, T2 y) {
  if (x < y) x = y;
}
const int MAXN = 2e5 + 10, INF = 1e9;
long long a[MAXN], c[MAXN];
bool used[MAXN];
int main() {
  int n;
  cin >> n;
  for (int i = 0; i < n; i++) {
    cin >> c[i];
  }
  for (int i = 0; i < n; i++) {
    cin >> a[i];
    a[i]--;
  }
  long long ans = 0;
  for (int i = 0; i < n; i++) {
    if (used[i]) continue;
    vector<int> path;
    int u = i;
    while (!used[u]) {
      used[u] = true;
      path.push_back(u);
      u = a[u];
    }
    long long add = c[u];
    while (!path.empty() && path.back() != u) {
      chkMin(add, c[path.back()]);
      path.pop_back();
    }
    if (!path.empty()) ans += add;
  }
  cout << ans;
}
