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
#include <iostream>
#include <vector>

using namespace std;

struct Nd {
	int p, c, n;
	Nd *nl = NULL, *np = NULL;
};

int odp = 0;
int n;

Nd* root[2];
void read_tree(int nt) {
	vector<Nd*> nodes(n);
	for (int i = 0;i < n;i++) {
		nodes[i] = new Nd();
		nodes[i]->p = i;
		nodes[i]->c = i;
		nodes[i]->n = i;
	}

	for (int i = 0;i < n;i++) {
		int t;
		cin >> t;
		t--;
		if (t == -2)
			root[nt] = nodes[i];
		else if (i < t)
			nodes[t]->nl = nodes[i];
		else
			nodes[t]->np = nodes[i];
	}
}

void merge(Nd* n){
	if (n->nl != NULL && n->nl->c == n->p - 1) {
		n->p = n->nl->p;
		n->nl = n->nl->nl;
	}

	if (n->np != NULL && n->np->c == n->n + 1) {
		n->n = n->np->n;
		n->np = n->np->np;
	}
}

void move_current(Nd* n, int c) {
	int t = n->c - c;
	if (t < 0) t = -t;
	odp += t;
	odp %= 1000000007;
	n->c = c;
}

bool can_move_current(Nd* n, int c) {
	return n->p <= c && n->n >= c;
}

void separete(Nd* n, Nd*& l, Nd*& p) {
	if (n->c != n->p) {
		l = new Nd();
		l->p = n->p;
		l->c = n->c - 1;
		l->n = n->c - 1;
		l->nl = n->nl;
	}
	else
		l = n->nl;

	if (n->c != n->n) {
		p = new Nd();
		p->n = n->n;
		p->c = n->c + 1;
		p->p = n->c + 1;
		p->np = n->np;
	}
	else
		p = n->np;
}

void reduce_right(Nd* n);

void reduce_left(Nd* n) {
	while (n->nl != NULL) {
		reduce_right(n->nl);
		merge(n);
	}
	move_current(n, n->p);
}

void reduce_right(Nd* n) {
	while (n->np != NULL) {
		reduce_left(n->np);
		merge(n);
	}
	move_current(n, n->n);
}

void set_val(Nd* n, int v) {
	while (!can_move_current(n, v)) {
		if (v < n->c)
			reduce_right(n->nl);
		else
			reduce_left(n->np);
		merge(n);
	}

	move_current(n, v);
}

void DFS(Nd* a, Nd* b) {
	set_val(a, b->c);
	Nd* l, * p;
	separete(a, l, p);
	if (b->nl != NULL)
		DFS(l, b->nl);
	if (b->np != NULL)
		DFS(p, b->np);
}

int main()
{
	cin >> n;
	read_tree(0);
	read_tree(1);
	DFS(root[0], root[1]);
	cout << odp;

}