1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
#include<bits/stdc++.h>
#define fi first
#define se second
using namespace std;
int MOD=1e9+7;
int par[2][500010];
int son[2][2][500010];
int siz[500010];
void pre(int x)
{
	siz[x]=1;
	for(int j:{0,1})
	{
		if(son[0][j][x]!=0)
		{
			pre(son[0][j][x]);
			siz[x]+=siz[son[0][j][x]];
		}
	}
	return;
}
int dp(int x,bool t)
{
	int ans=0;
	if(son[0][0][x]!=0)
		ans=(ans+dp(son[0][0][x],0))%MOD;
	if(son[0][1][x]!=0)
		ans=(ans+dp(son[0][1][x],1))%MOD;
	if(son[0][!t][x]!=0)
		ans=(ans+siz[son[0][!t][x]])%MOD;
	return ans;
}
int solve(int r1,int r2,int en,int sub,bool t)
{
	//cerr<<"r1="<<r1<<" r2="<<r2<<" en="<<en<<" sub="<<sub<<" t="<<t;
	int ans=0,rr1,rr2,en1,en2,sub1,sub2;
	//solve myself
	if((r1==sub)&&(r1==r2))
	{
		rr1=en1=sub1=son[0][0][r1];
		rr2=en2=sub2=son[0][1][r1];
	}
	else if(min(r1,en)<=r2 && r2<=max(r1,en))
	{
		ans=abs(r2-r1);
		if(t)
		{
			rr1=r2-1;
			en1=r1;
			sub1=0;
			rr2=(r2==en ? sub:r2+1);
			en2=(r2==en ? sub:en);
			sub2=sub;
		}
		else
		{
			rr1=(r2==en ? sub:r2-1);
			en1=(r2==en ? sub:en);
			sub1=sub;
			rr2=r2+1;
			en2=r1;
			sub2=0;
		}
	}
	else
	{
		int tmp=-1;
		if(r1==sub)
			t=(r2>r1);
		for(int x=r2;x!=en;x=par[0][x])
		{
			if(x==son[0][!t][par[0][x]])
				tmp=-1;
			else if(tmp==-1)
				tmp=x;
		}
		for(int x=tmp;x!=en;x=par[0][x])
		{
			if(son[0][!t][x]!=0)
				ans=(ans+dp(son[0][!t][x],!t)+siz[son[0][!t][x]])%MOD;
		}
		ans=(ans+abs(r1-r2))%MOD;
		if(t)
		{
			rr1=r2-1;
			en1=r1;
			sub1=(r1==sub ? son[0][0][r1]:0);
			rr2=(r2==tmp ? son[0][1][tmp]:r2+1);
			en2=(r2==tmp ? son[0][1][tmp]:tmp);
			sub2=son[0][1][tmp];
		}
		else
		{
			rr1=(r2==tmp ? son[0][0][tmp]:r2-1);
			en1=(r2==tmp ? son[0][0][tmp]:tmp);
			sub1=son[0][0][tmp];
			rr2=r2+1;
			en2=r1;
			sub2=(r1==sub ? son[0][1][r1]:0);
		}
	}
	//cerr<<" ans_myself="<<ans<<"\n";
	//solve sons
	if(son[1][0][r2]!=0)
		ans=(ans+solve(rr1,son[1][0][r2],en1,sub1,0))%MOD;
	if(son[1][1][r2]!=0)
		ans=(ans+solve(rr2,son[1][1][r2],en2,sub2,1))%MOD;
	return ans;
}
int main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);
	int n,i;
	cin>>n;
	for(int j:{0,1})
	{
		for(i=1;i<=n;i++)
		{
			cin>>par[j][i];
			if(par[j][i]==-1)
			{
				par[j][i]=0;
				son[j][1][0]=i;
			}
			else if(i<par[j][i])
				son[j][0][par[j][i]]=i;
			else
				son[j][1][par[j][i]]=i;
		}
	}
	pre(0);
	cout<<(solve(0,0,0,son[0][1][0],1)+MOD)%MOD<<"\n";
	return 0;
}