#include <fstream>
#include <iostream>
#include <cassert>
#include <cstring>
#include <vector>
#include <algorithm>
#include <cassert>

using namespace std;

const int maxN = 100000;
const int maxTr = (1 << 18);

struct evt {
  int x, y1, y2, r;
  evt() {
  }
  evt( int _x, int _y1, int _y2, int _r ):
    x(_x), y1(_y1), y2(_y2), r(_r) {
  }
  bool operator < ( const evt &b ) const {
    if (x != b.x) {
      return x < b.x;
    }
    return r < b.r;
  }
};

int n, p[2][maxN], root[2], tIn[2][maxN], tOut[2][maxN], t[2];
vector <int> to[2][maxN];
vector <evt> e;
int tr[maxTr * 2];

void addP( int x, int y ) {
  e.push_back(evt(x, y, y, 0));
}

void addR( int x1, int x2, int y1, int y2 ) {
  assert(x1 < x2);
  assert(y1 < y2);
  e.push_back(evt(x1, y1, y2, -1));
  e.push_back(evt(x2, y1, y2, 1));
}

void addE( vector <int> to[], int a, int b ) {
  to[a].push_back(b);
}

void dfs( const vector <int> to[], int tIn[], int tOut[], int &t, int v ) {
  tIn[v] = t++;
  for (int i = 0; i < (int)to[v].size(); i++) {
    int w = to[v][i];
    dfs(to, tIn, tOut, t, w);
  }
  tOut[v] = t++;
}

void inc( int x, int d ) {
  x += maxTr;
  while (x > 0) {
    tr[x] += d;
    x = x / 2;
  }
}

int get( int x1, int x2 ) {
  x1 += maxTr;
  x2 += maxTr;
  if (x1 == x2) {
    return tr[x1];
  }
  int ans = tr[x1] + tr[x2];
  while (x1 / 2 < x2 / 2) {
    if (!(x1 & 1)) {
      ans += tr[x1 + 1];
    }
    if (x2 & 1) {
      ans += tr[x2 - 1];
    }
    x1 /= 2;
    x2 /= 2;
  }
  return ans;
}

int main() {
  ifstream fin("virus.in");
  ofstream fout("virus.out");

  assert(fin >> n);
  assert(n <= 100);
  for (int j = 0; j < 2; j++) {
    root[j] = -1;
    for (int i = 0; i < n; i++) {
      assert(fin >> p[j][i]);
      p[j][i]--;
      if (p[j][i] == -1) {
        assert(root[j] == -1);
        root[j] = i;
      } else {
        addE(to[j], p[j][i], i);
      }
    }
//    cerr << "j=" << j << endl;
    t[j] = 0;
    dfs(to[j], tIn[j], tOut[j], t[j], root[j]);
  }

//  cerr << "stage 1" << endl;

  for (int i = 0; i < n; i++) {
    addP(tIn[0][i], tIn[1][i]);
    addR(tIn[0][i], tOut[0][i], tIn[1][i], tOut[1][i]);
  }
  sort(e.begin(), e.end());
  
//  cerr << "stage 2" << endl;

  memset(tr, 0, sizeof(tr));
  long long ans = 0;
  for (int i = 0; i < (int)e.size(); i++) {
    evt &ev = e[i];
    if (ev.r == 0) {
//      cerr << "inc(" << ev.y1 << ")" << endl;
      inc(ev.y1, 1);
    } else {
//      cerr << "get(" << ev.y1 << ", " << ev.y2 << ")=" << get(ev.y1, ev.y2) << "*" << ev.r << endl;
      ans += get(ev.y1, ev.y2) * ev.r;
    }
  }
  
//  cerr << "stage 3" << endl;
  
  fout << (ans - n) << endl;

  return 0;
}
