#include <bits/stdc++.h>
using namespace std;
vector<int> cost;
vector<int> g;
int n;
vector<int> visited;
int ans = 0;
void dfs(int x, vector<int>& t) {
  visited[x] = 2;
  if (!visited[g[x]]) {
    t.push_back(x);
    dfs(g[x], t);
    t.pop_back();
  }
  if (visited[g[x]] == 2) {
    t.push_back(x);
    int currcost = cost[x];
    for (int j = t.size() - 1; j >= 0; j--) {
      currcost = min(currcost, cost[t[j]]);
      if (t[j] == g[x]) break;
    }
    t.pop_back();
    ans += currcost;
  }
  visited[x] = 1;
  return;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cin >> n;
  g.resize(n);
  cost.resize(n);
  for (int i = 0; i < n; i++) {
    cin >> cost[i];
  }
  for (int i = 0; i < n; i++) {
    cin >> g[i];
    g[i]--;
  }
  visited.resize(n);
  for (int i = 0; i < n; i++) {
    if (!visited[i]) {
      vector<int> temp;
      dfs(i, temp);
    }
  }
  cout << ans;
  return 0;
}
