#include <bits/stdc++.h>
using namespace std;
int nxt[200010], vis[200010], cost[200010];
int n, fp, minn;
int find(int x) {
  int minn = cost[x];
  for (int i = nxt[x];; i = nxt[i]) {
    if (i == x)
      return minn;
    else
      minn = min(minn, cost[i]);
  }
}
int main() {
  cin >> n;
  for (int i = 0; i < n; i++) cin >> cost[i];
  for (int i = 0; i < n; i++) {
    cin >> nxt[i];
    nxt[i]--;
    if (nxt[i] == i) {
      fp += cost[i];
      vis[i] = -1;
    }
  }
  for (int i = 0; i < n; i++) {
    if (vis[i] != 0) continue;
    minn = cost[i];
    for (int j = i;; j = nxt[j]) {
      if (vis[j] != 0) {
        if (vis[j] == i + 1) fp += find(j);
        break;
      }
      vis[j] = i + 1;
      minn = min(minn, cost[j]);
    }
  }
  cout << fp;
  return 0;
}
