#include <bits/stdc++.h>
using namespace std;
const long long MOD = (long long)1e9 + 7;
const long long MAXN = (long long)200010;
long long n;
int c[MAXN];
int a[MAXN];
char u[MAXN] = {};
int dfs(int v, vector<int> &p) {
  u[v] = 1;
  p.push_back(v);
  int x = a[v];
  {
    if (u[x] == 1) {
      int b = 0;
      for (int i = 0; i < p.size(); ++i) {
        if (p[i] == x) b = i;
        u[p[i]] = 2;
      }
      int mn = INT_MAX;
      for (int i = b; i < p.size(); ++i) {
        mn = min(mn, c[p[i]]);
      }
      for (int i = 0; i < p.size(); ++i) {
        c[p[i]] = mn;
      }
      u[v] = 2;
      c[x] = mn;
      c[v] = mn;
      u[x] = 2;
      return mn;
    }
    if (u[x] == 2) {
      u[v] = 2;
      return 0;
    }
    if (u[x] == 0) {
      long long z = dfs(x, p);
      u[v] = 2;
      return z;
    }
  }
  u[v] = 2;
  return c[v];
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(NULL);
  cout.tie(NULL);
  cin >> n;
  for (int i = 0; i < n; ++i) cin >> c[i];
  for (int i = 0; i < n; ++i) {
    int x;
    cin >> x;
    --x;
    a[i] = x;
  }
  long long ans = 0;
  for (int i = 0; i < n; ++i) {
    if (u[i] == 0) {
      vector<int> p;
      ans += dfs(i, p);
      p.clear();
    }
  }
  cout << ans << endl;
  return 0;
}
