#include <bits/stdc++.h>
using namespace std;
const int N = 2 * 1e5 + 2;
int n, x, ans, idx;
int cost[N], neigh[N], used[N];
vector<int> go;
void dfs(int curr) {
  used[curr] = 1;
  go.push_back(curr);
  if (used[neigh[curr]] == 0)
    dfs(neigh[curr]);
  else if (used[neigh[curr]] == 1) {
    x = INT_MAX;
    for (idx = (int)go.size() - 1; go[idx] != neigh[curr]; idx--)
      x = min(x, cost[go[idx]]);
    x = min(x, cost[neigh[curr]]);
    ans += x;
  }
  go.pop_back();
  used[curr] = 2;
}
int main() {
  ios::sync_with_stdio(false), cin.tie(NULL);
  cin >> n;
  for (int i = 1; i <= n; ++i) cin >> cost[i];
  for (int i = 1; i <= n; ++i) cin >> neigh[i];
  for (int i = 1; i <= n; ++i) {
    if (used[i] == 0) {
      dfs(i);
    }
  }
  cout << ans << '\n';
  return 0;
}
