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
#include <bits/stdc++.h>
#define REP(i,n) for(int _n=(n), i=0;i<_n;++i)
#define FOR(i,a,b) for(int i=(a),_b=(b);i<=_b;++i)
#define FORD(i,a,b) for(int i=(a),_b=(b);i>=_b;--i)
using std::vector;

void init_io() {
  std::cin.tie(nullptr);
  std::ios::sync_with_stdio(false);
}

struct Vertex {
  // [era][dir]
  // no child = self loop
  int children[2][2] = {};
  int flatten_delta = 0;
};

int num_vertices;
vector<Vertex> vertices;

void read_input() {
  std::cin >> num_vertices;
  ++num_vertices;
  vertices.resize(num_vertices);

  REP(i,num_vertices) REP(era,2) REP(dir,2) {
    vertices[i].children[era][dir] = i;
  }

  REP(era, 2) {
    FOR(i,1,num_vertices-1) {
      int parent;
      std::cin >> parent;
      if (parent == -1) parent=0;
      vertices[parent].children[era][i > parent] = i;
    }
  }
}

int64_t solve() {
  for (const Vertex &vertex : vertices) {
    REP(dir, 2) {
      int a = vertex.children[0][dir];
      int b = vertex.children[1][dir];
      if (a > b) std::swap(a, b);
      vertices[a].flatten_delta += 1;
      vertices[b].flatten_delta -= 1;
    }
  }

  int64_t result = 0;
  int flatten = 0;

  REP(i, num_vertices) {
    const Vertex &vertex = vertices[i];

    REP(dir, 2) {
      if (dir==1) flatten += vertices[i].flatten_delta;
      if (flatten) {
        REP(era, 2) {
          result += std::max(0, std::abs(vertex.children[era][dir] - i) - 1);
        }
      } else {
        result += std::abs(vertex.children[0][dir] - vertex.children[1][dir]);
      }
    }
  }

  return result;
}

int main() {
  init_io();

  read_input();
  int64_t res = solve();
  res %= 1'000'000'007;
  std::cout << res << "\n";
}