#include<iostream>
using namespace std;
int i,n,u,maxx=-1e9;
struct node{
int l,r,v;
}a[1000010];
bool tree(int l,int r){
if(l==-1&&r==-1){
return true;
}else if(l*r<0){
return false;
}else{
if(a[l].v!=a[r].v){
return false;
}
int l1=a[l].l,r1=a[r].r,l2=a[l].r,r2=a[r].l;
if(tree(l1,r1)==true&&tree(l2,r2)==true){
return true;
}else{
return false;
}
}
}
int len(int x){
if(x==-1){
return 0;
}else{
return len(a[x].l)+len(a[x].r)+1;
}
}
void p(int x){
if(x!=-1){
//cout<<x<<" "<<maxx<<" ";
if(tree(a[x].l,a[x].r)==true){
maxx=max(maxx,len(x));
}
p(a[x].l);
p(a[x].r);
}
}
int main(){
cin>>n;
for(i=1;i<=n;i++){
a[i].v=-1;
a[i].r=-1;
a[i].l=-1;
}
for(i=1;i<=n;i++){
cin>>u;
a[i].v=u;
}
int ll,rr;
for(i=1;i<=n;i++){
cin>>ll>>rr;
a[i].l=ll;
a[i].r=rr;
}
//cout<<tree(a[1].l,a[1].r);
p(1);
//cout<<len(10);
/*3
3 2 2
2 3
-1 -1
-1 -1*/
cout<<maxx;
return 0;
}