#include <bits/stdc++.h>
using namespace std;
const int mod = 998244353;
const long long int inf = 1e12;
const long long int N = 1e5 + 5;
long long int C[2 * N];
long long int A[2 * N];
long long int done[2 * N];
vector<long long int> v;
vector<vector<long long int>> cycle;
long long int dfs(long long int a) {
  done[a] = 1;
  v.push_back(a);
  long long int j = A[a];
  if (done[j] != 2) {
    if (done[j] == 1) {
      cycle.emplace_back();
      long long int id = v.size() - 1;
      while (v[id] != j) {
        cycle.back().push_back(v[id]);
        id--;
      }
      cycle.back().push_back(j);
    } else {
      dfs(j);
    }
  }
  v.pop_back();
  done[a] = 2;
  return 0;
}
long long int solve(long long int fu) {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  long long int n;
  cin >> n;
  for (long long int i = 0; i < n; i++) cin >> C[i];
  for (long long int i = 0; i < n; i++) {
    cin >> A[i], A[i]--;
  }
  fill(done, done + (2 * N), 0);
  for (long long int i = 0; i < n; i++) {
    if (!done[i]) {
      dfs(i);
    }
  }
  long long int ans = 0;
  for (auto curr : cycle) {
    long long int mk = inf;
    for (auto j : curr) {
      mk = min(mk, C[j]);
    }
    ans += mk;
  }
  cout << ans;
  return 0;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  long long int t;
  t = 1;
  while (t) {
    solve(t);
    t--;
  }
  return 0;
}
