#include <bits/stdc++.h>
using namespace std;
const int MAX_N = 2e5 + 7;
int n, c[MAX_N], a[MAX_N], d[MAX_N];
bool visited[MAX_N];
stack<int> GStack;
int dfs(int u) {
  if (!visited[u]) {
    GStack.push(u);
    visited[u] = true;
    int res = dfs(a[u]);
    c[u] = 0;
    return res;
  }
  if (!c[u]) return 0;
  int bestCost = 1e4;
  for (int v = 0; v != u; c[v] = 0) {
    bestCost = min(bestCost, c[v = GStack.top()]);
    if (GStack.size()) GStack.pop();
  }
  GStack.push(u);
  return bestCost;
}
int main() {
  ios_base::sync_with_stdio(false);
  cout.tie(nullptr), cin.tie(nullptr);
  cin >> n;
  for (int i = 1; i <= n; ++i) cin >> c[i];
  for (int i = 1; i <= n; ++i) cin >> a[i], ++d[a[i]];
  long long ans = 0;
  for (int i = 1; i <= n; ++i)
    if (d[i] != 0) ans += dfs(i);
  cout << ans << "\n";
  cerr << "Esc Time: " << clock() << " ms\n";
  return 0;
}
