#include <iostream>
#include <fstream>
#include <cassert>
#include <cstdlib>
#include <cmath>
#include <map>
#include <set>
#include <algorithm>
#include <vector>
#include <queue>
#include <list>
#include <cstring>

#define all(x) (x).begin(),(x).end()

using namespace std;

const int nmax = 1e6;

vector <int> g[nmax];
vector <int> gt[nmax];

vector < pair<int,int> > add_event[nmax];
vector < pair<int,int> > del_event[nmax];
vector <int> req_event[nmax];

int tin1[nmax];
int tin2[nmax];
int tout1[nmax];
int tout2[nmax];
bool used[nmax];

int timer;
int n;

struct FenvickTree
{
	int array[nmax];
	int sum(int pos)
	{
		int result = 0;
		for (; pos >= 0; pos = (pos & (pos + 1)) - 1)
			result += array[pos];
		return result;
	};
	int add(int pos, int value)
	{
		for (; pos < nmax; pos = pos | (pos + 1))
			array[pos] += value;
	}
};

FenvickTree tree;

void dfs(int v, const vector<int> * g, int* tin, int* tout)
{
	used[v] = 1;
	tin[v] = timer ++;
	for (int i = 0; i < g[v].size(); i ++)
	{
		int u = g[v][i];
		if (!used[u])
			dfs(u, g, tin, tout);
	}
	tout[v] = timer ++;
};

int main()
{
	freopen("virus.in","r",stdin);
	freopen("virus.out","w",stdout);
	scanf("%d", &n);
	int root1 = -1, root2 = -1;
	for (int i = 0; i < n; i ++)
	{
		int u;
		scanf("%d", &u);
		u --;
		if (u != -1)
			g[u].push_back(i);
		else
			root1 = i;
	}
	for (int i = 0; i < n; i ++)
	{
		int u;
		scanf("%d", &u);
		u --;
		if (u != -1)
			gt[u].push_back(i);
		else
			root2 = i;
	}
	timer = 0; dfs(root1, g, tin1, tout1);
	memset(used, 0, sizeof(used));
	timer = 0; dfs(root2, gt, tin2, tout2);
	for (int v = 0; v < n; v ++)
	{
		add_event[tin1[v]].push_back(make_pair(tin2[v], tout2[v] + 1));
		del_event[tout1[v]].push_back(make_pair(tin2[v], tout2[v] + 1));
		req_event[tin1[v]].push_back(tin2[v]);
	};
	long long result = 0;
	for (int t = 0; t < nmax; t ++)
	{
		for (int i = 0; i < add_event[t].size(); i ++)
		{
			tree.add(add_event[t][i].first, 1);
			tree.add(add_event[t][i].second, -1);
		}
		for (int i = 0; i < req_event[t].size(); i ++)
			result += tree.sum(req_event[t][i]);
		for (int i = 0; i < del_event[t].size(); i ++)
		{
			tree.add(del_event[t][i].first, -1);
			tree.add(del_event[t][i].second, 1);
		}
	}
	cout << (result - n) << endl;
	return 0;
};
