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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
#include <cstdio>
#include <cstdlib>
// #include <cassert>

#include <vector>

static const unsigned int MODULUS = 1000 * 1000 * 1000 + 7;

struct node {
    int parent;
    int left;
    int right;

    unsigned int size;
    unsigned int left_lin, right_lin; // Linearization cost
};

node ltree[500 * 1000 + 1] = { 0 };
node rtree[500 * 1000 + 1] = { 0 };

int stack[500 * 1000 + 1];

int read_tree(node *tree, int n) {
    int root = -1;

    for (int i = 1; i <= n; i++) {
        int parent;
        scanf("%d", &parent);
        tree[i].parent = parent;
        if (parent == -1) {
            root = i;
        }
        if (parent > i) {
            tree[parent].left = i;
        } else {
            tree[parent].right = i;
        }
    }

    return root;
}

struct visitor_base {
    bool pre_order(int idx) {
        return true;
    }
    bool in_order(int idx) {
        return true;
    }
    void post_order(int idx) {}
};

// TODO: This can be made stackless?
template<typename V>
void visit_tree(node *tree, int root, V visitor) {
    int sdepth = 1;
    stack[0] = root << 2;

    while (sdepth > 0) {
        const int curr = stack[sdepth - 1] >> 2;
        const int progress = stack[sdepth - 1] & 3;

        if (curr == 0) {
            sdepth--;
            continue;
        }

        stack[sdepth - 1]++;
        if (progress == 0) {
            if (visitor.pre_order(curr)) {
                stack[sdepth++] = tree[curr].left << 2;
            } else {
                sdepth--;
            }
        } else if (progress == 1) {
            if (visitor.in_order(curr)) {
                stack[sdepth++] = tree[curr].right << 2;
            } else {
                sdepth--;
            }
        } else {
            visitor.post_order(curr);
            sdepth--;
        }
    }
}

void precompute_parameters(node *tree, int root) {
    struct precomputer : public visitor_base {
        node *tree;
        int root;

        precomputer(node* tree, int root)
            : visitor_base()
            , tree(tree)
            , root(root)
        {}

        void post_order(int idx) {
            tree[idx].size =
                1
                + tree[tree[idx].left].size
                + tree[tree[idx].right].size;
            tree[idx].size %= MODULUS;
            
            tree[idx].left_lin =
                tree[tree[idx].left].left_lin
                + tree[tree[idx].right].right_lin
                + tree[tree[idx].right].size;
            tree[idx].left_lin %= MODULUS;

            tree[idx].right_lin =
                tree[tree[idx].right].right_lin
                + tree[tree[idx].left].left_lin
                + tree[tree[idx].left].size;
            tree[idx].right_lin %= MODULUS;
        }
    };

    visit_tree(tree, root, precomputer{tree, root});
}

unsigned int compute_total_cost(int lroot, int rroot) {
    struct state {
        int lnode, rnode;
        int extrude;
        int dir_from;
    };

    std::vector<state> st;

    st.push_back(state {
        lroot, rroot,
        0, -1
    });

    unsigned int ops = 0;

    while (!st.empty()) {
        const state s = st.back();
        st.pop_back();

        int lnode = s.lnode;
        int rnode = s.rnode;
        int extrude = s.extrude;
        const int dir_from = s.dir_from;

        if (lnode == 0 && rnode == 0) {
            continue;
        }

        int balance, llnode, lrnode, rlnode, rrnode;

        rlnode = rtree[rnode].left;
        rrnode = rtree[rnode].right;

        if (extrude == 0) {
            llnode = ltree[lnode].left;
            lrnode = ltree[lnode].right;
            balance = ltree[llnode].size - rtree[rlnode].size;
        } else if (dir_from < 0) {
            llnode = lnode;
            lrnode = 0;
            balance = ltree[lnode].size + extrude - 1 - rtree[rlnode].size;
        } else {
            llnode = 0;
            lrnode = lnode;
            balance = 0 - rtree[rlnode].size;
        }

        // printf("At %d %d\n", s.lnode, s.rnode);
        // printf("  balance: %d\n", balance);
        // printf("  extrude: %d\n", extrude);
        // printf("  dir: %d\n", dir_from);
        // printf("  lsize: %d\n", ltree[lnode].size);
        // printf("  rsize: %d\n", rtree[rnode].size);

        // assert(ltree[lnode].size + extrude == rtree[rnode].size);

        // Now, extrude tells us how many verts we can push to the other side
        if (extrude > 0) {
            extrude--;
        }

        if (balance > 0 || (balance == 0 && dir_from < 0)) {
            //       lnode
            //        /
            //       / <- extrusion
            //      /
            //     .
            //    / \
            // ...   ...

            // Assume that we moved the needed amount of nodes to the right, and compute balance for that
            // printf("    pushing right %d\n", balance);
            st.push_back(state { lrnode, rrnode, balance, 1 });

            while (extrude < balance) {
                // Linearize its right subtree, and then move the the left path
                const int rch = ltree[llnode].right;
                extrude += 1 + ltree[rch].size;
                ops = (ops + ltree[rch].right_lin + ltree[rch].size) % MODULUS;

                // printf("    right-linearizing %d, cost: %d + %d\n", rch, ltree[rch].right_lin, ltree[rch].size);

                // Advance to the next vertex on the left
                llnode = ltree[llnode].left;
            }

            // Move `extrude` elements from the left path, using rotations, to the right subtree
            extrude -= balance;
            ops = (ops + balance) % MODULUS;

            // Compute left subtree
            // printf("    pushing left %d\n", extrude);
            st.push_back(state { llnode, rlnode, extrude, -1 });
        } else {
            // lnode
            //    \
            //     \ <- extrusion
            //      \ 
            //       .
            //      / \
            //   ...   ...
            balance = -balance;

            // Assume that we moved the needed amount of nodes to the left, and compute balance for that
            // printf("    pushing left %d\n", balance);
            st.push_back(state { llnode, rlnode, balance, -1 });

            while (extrude < balance) {
                // Linearize its left subtree, and then move the the right path
                const int lch = ltree[lrnode].left;
                extrude += 1 + ltree[lch].size;
                ops = (ops + ltree[lch].left_lin + ltree[lch].size) % MODULUS;

                // printf("    left-linearizing %d, cost: %d + %d\n", lch, ltree[lch].left_lin, ltree[lch].size);

                // Advance to the next vertex on the right
                lrnode = ltree[lrnode].right;
            }

            // Move `extrude` elements from the right path, using rotations, to the left subtree
            extrude -= balance;
            ops = (ops + balance) % MODULUS;

            // Compute right subtree
            // printf("    pushing right %d\n", extrude);
            st.push_back(state { lrnode, rrnode, extrude, 1 });
        }

        // printf("  cost -> %u\n", ops);
    }

    return ops;
}

int main() {
    int n;
    scanf("%d", &n);

    const int lroot = read_tree(ltree, n);
    const int rroot = read_tree(rtree, n);

    precompute_parameters(ltree, lroot);
    precompute_parameters(rtree, rroot);

    unsigned int result = compute_total_cost(lroot, rroot);
    printf("%u\n", result);

    return 0;
}