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

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

using namespace std;

const int nmax = 1e6;

int ind[nmax];
int used[nmax];
int lowlink[nmax];

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


int n;

int curind = 0;
long long res = 0;

void dfs(int v)
{
	ind[v] = curind ++;
	used[v] = 1;
	lowlink[v] = ind[v];
	st.push_back(v);
	for (int i = 0; i < g[v].size(); i ++)
	{
		int u = g[v][i];
		if (used[u] == 0)
		{
			dfs(u);
			lowlink[v] = min(lowlink[v], lowlink[u]);
		}
		if (used[u] == 1)
			lowlink[v] = min(lowlink[v], ind[u]);
	}
	if (lowlink[v] == ind[v])
	{
			int w;
			int sz = 0;
			do
			{
				w = st.back(); st.pop_back();
				sz ++;
			}
			while (w != v);
			res += (long long)(sz) + (long long)(sz - 1)* (long long)(sz) / 2;
		}
	used[v] = 2;
};



int main()
{
        freopen("virus.in", "r", stdin);
        freopen("virus.out", "w", stdout);
	scanf("%d\n", &n);
	for (int v = 0; v < n; v ++)
	{
		int u;
		scanf("%d", &u);
		u --;
		if (u != -1)
			g[v].push_back(u);
	}		
	for (int v = 0; v < n; v ++)
	{
		int u;
		scanf("%d", &u);
		u --;
		if (u != -1)
			g[u].push_back(v);
	}		
	for (int i = 0; i < n; i++)
		if (!used[i])
			dfs(i);
	cout << (res - n) << endl;
	return 0;
};
