#include <bits/stdc++.h>
using namespace std;
const long double Pi = 3.14159265359;
const long MOD = (long)1e9 + 7;
long long const MAXN = (long long)1e6 + 10;
long long se[MAXN];
long long nex[MAXN];
long long c[MAXN];
long long vi[MAXN];
vector<long long> vis;
int main() {
  ios::sync_with_stdio(0);
  long long n;
  cin >> n;
  long long x;
  for (int i = 0; i < n; i++) cin >> c[i];
  for (int i = 0; i < n; i++) {
    cin >> x;
    nex[i] = x - 1;
  }
  long long m, po, out = 0;
  for (int i = 0; i < n; i++) {
    if (se[i] == 1) continue;
    po = i;
    while (true) {
      if (se[po] == 1) {
        while (vis.size() > 0) {
          se[vis.back()] = 1;
          vis.pop_back();
        }
        break;
      }
      if (vi[po] == 1) {
        m = c[po];
        se[po] = 1;
        while (vis.back() != po) {
          se[vis.back()] = 1;
          m = min(m, c[vis.back()]);
          vis.pop_back();
        }
        out += m;
        while (vis.size() > 0) {
          se[vis.back()] = 1;
          vis.pop_back();
        }
        break;
      }
      vis.push_back(po);
      vi[po] = 1;
      po = nex[po];
    }
  }
  cout << out;
  return 0;
}
