#include <bits/stdc++.h>
using namespace std;
int n;
int c[200000];
int a[200000];
int ind[200000];
int visited[200000], parent[200000];
int mini[200000];
long long ans;
void dfs(int begin) {
  stack<int> pila;
  pila.push(begin);
  while (!pila.empty()) {
    int u = pila.top();
    pila.pop();
    visited[u] = 1;
    int v = a[u];
    if (!visited[v]) {
      parent[v] = u;
      pila.push(v);
    } else {
      if (mini[v] != -1) {
        while (u != -1) {
          mini[u] = mini[v];
          u = parent[u];
        }
      } else {
        int minimum = c[v];
        while (u != v) {
          minimum = min(c[u], minimum);
          u = parent[u];
        }
        ans += minimum;
        int cnt = 0;
        int cur = begin;
        while (cnt < 2) {
          mini[cur] = 1;
          if (cur == v) cnt++;
          cur = a[cur];
        }
      }
      break;
    }
  }
}
int main() {
  scanf("%d", &n);
  for (int i = 0; i < n; i++) {
    scanf("%d", &c[i]);
  }
  memset(mini, -1, sizeof(mini));
  memset(parent, -1, sizeof(parent));
  for (int i = 0; i < n; i++) {
    scanf("%d", &a[i]);
    a[i]--;
    if (a[i] == i) {
      mini[a[i]] = c[i];
      visited[i] = 1;
      ans += c[i];
    }
    ind[a[i]]++;
  }
  for (int i = 0; i < n; i++) {
    if (ind[i] == 0) {
      dfs(i);
    }
  }
  for (int i = 0; i < n; i++) {
    if (!visited[i]) dfs(i);
  }
  printf("%lld\n", ans);
  return 0;
}
