#include <iostream>
#include <fstream>
#include <vector>
#include <set>
#include <map>
#include <string>
#include <cmath>
#include <cassert>
#include <ctime>
#include <algorithm>
#include <queue>
#include <memory.h>
#include <stack>
#define mp make_pair
#define pb push_back                     
#define setval(a,v) memset(a,v,sizeof(a))

#if ( _WIN32 || __WIN32__ )
    #define LLD "%I64d"
#else
    #define LLD "%lld"
#endif

using namespace std;

typedef long long ll;
typedef long double ld;

const int MAXN = 110000;

vector<int> g[MAXN][2];
int n;

int tin[MAXN][2];
int tout[MAXN][2];
int timer[2];

void dfs(int v,int gr){
    tin[v][gr] = ++timer[gr];

    for (int i = 0; i < (int)g[v][gr].size(); i++)
        dfs(g[v][gr][i],gr);

    tout[v][gr] = ++timer[gr];
}

struct event{
    int type;
    int x;
    int ly,ry;
    event(int type,int x,int ly,int ry):type(type),x(x),ly(ly),ry(ry){        
    }
    event(int type,int x,int ly):type(type),x(x),ly(ly),ry(ly){        
    }
    event(){
    }
    bool operator<(const event& r)const{
        if (x != r.x)
            return x < r.x;
        return type < r.type;
    }
};

vector<event> evs;

int tree[8*MAXN];
int lst;

void init(int n){
    lst = 2;
    while (lst < n)
        lst *= 2;
}

void update(int pos,int val){
    pos += lst;
    tree[pos] += val;
    for (pos/=2;pos; pos/=2)
        tree[pos] = tree[2*pos] + tree[2*pos+1];
}

int get(int v,int l,int r,int L,int R){
    if (r < L || R < l)
        return 0;
    if (L <= l && r <= R)
        return tree[v];
    return get(2*v,l,(l+r)/2,L,R) + get(2*v+1,(l+r)/2+1,r,L,R);
}

int main(){
  freopen("virus.in","r",stdin);
  freopen("virus.out","w",stdout);

  scanf("%d",&n);

  for (int it = 0; it < 2; it++){
     int r = -1;
     for (int i = 0; i < n; i++){
       int p;
       scanf("%d",&p);
       --p;
       if (p == -1)
           r = i;
       else
           g[p][it].pb(i);
     } 
     dfs(r,it);
  }


  for (int i = 0; i < n; i++){
    evs.pb(event(0,tin[i][0],tin[i][1]));
    evs.pb(event(-1,tin[i][0],tin[i][1],tout[i][1]));
    evs.pb(event(1,tout[i][0],tin[i][1],tout[i][1]));
  }

  sort(evs.begin(),evs.end());

  ll ans = 0;

  init(2*n);

  for (int i = 0; i < (int)evs.size(); i++){
    if (evs[i].type == 0)
        update(evs[i].ly,1);
    else
        ans += get(1,0,lst-1,evs[i].ly,evs[i].ry)*evs[i].type;        
  }

  cout << (ans - n) << endl;
  return 0;
}

