#include <bits/stdc++.h>
using namespace std;
const long long INF = 1e18 + 10;
const int inf = 1e9 + 10;
const int N = 2e5;
vector<int> cost(N), used(N), g[N], way;
int ans;
void dfs(int v) {
  if (used[v] != 2) {
    way.push_back(v);
    if (!used[v]) {
      used[v] = 1;
      for (int i = 0; i < g[v].size(); i++) dfs(g[v][i]);
    } else {
      int mn = inf, ok = 0;
      for (int i = way.size() - 1; i >= 0 and ok < 2; i--) {
        if (way[i] == v) ok++;
        mn = min(mn, cost[way[i]]);
      }
      ans += mn;
    }
    used[v] = 2;
    way.pop_back();
  }
}
int main() {
  cin.tie(0);
  ios::sync_with_stdio(0);
  int n;
  cin >> n;
  for (int i = 0; i < n; i++) cin >> cost[i];
  for (int i = 0; i < n; i++) {
    int to;
    cin >> to;
    to--;
    g[i].push_back(to);
  }
  for (int i = 0; i < n; i++)
    if (!used[i]) dfs(i);
  cout << ans << "\n";
  return 0;
}
