Under construction

Still being built. Things may change

In-order

Time limit1sMemory limit1024 MB

Summary
Count the distinct in-order traversals of binary trees matching given pre-order, post-order, and partial in-order lists, modulo 999999937.
Level

Hard8 of 10

Topics
Tree, Divide and conquer, Combinatorics
Solved
No attempts yet

Problem

The opening ceremony for the Olympic Games will take place on the river with teams on boats. The layout of the athletes on top of the boat has been designed in a very specific way: for each team, the NN athletes (numbered from 11 to NN) are arranged as a binary tree.

The organiser has also designed the pre-order traversal, post-order traversal, and a (possibly empty) consecutive part of the in-order traversal of the binary tree that each team must follow.

Now, so that each team can have a distinct tree layout, calculate the number of different possible in-order traversals, TT, modulo the prime number 999 999 937999\,999\,937.

Input

The input consists of four lines. The first line contains the number NN. Each of the next three lines contains NN space-separated integers.

The second line contains A1,A2,…,ANA_1, A_2, \dots, A_N, where AkA_k is the number of the kkth athlete in pre-order traversal.

The third line contains B1,B2,…,BNB_1, B_2, \dots, B_N, where BkB_k is the number of the kkth athlete in post-order traversal.

The fourth line contains C1,C2,…,CNC_1, C_2, \dots, C_N, where CkC_k is the number of the kkth athlete in in-order traversal, or 00 if the organiser did not specify that athlete.

Output

The output is a single line containing a single integer SS, the only integer such that 0≤S<999 999 9370 \le S < 999\,999\,937 and T−ST - S is divisible by 999 999 937999\,999\,937.

Constraints

  • 1≤N≤500 0001 \le N \le 500\,000
  • There exists at least one binary tree with such pre-order, post-order, and in-order traversals.
  • The indices kk for which Ck≥1C_k \ge 1 form a (possibly empty) sub-interval of {1,2,…,N}\{1, 2, \dots, N\}. In other words, if k≤ℓk \le \ell and both CkC_k and CℓC_\ell are positive, then all of Ck,Ck+1,…,CℓC_k, C_{k+1}, \dots, C_\ell are positive.

Examples3

  1. Example 1

    Input
    8
    1 2 3 5 6 4 7 8
    5 6 3 8 7 4 2 1
    0 0 6 2 4 0 0 0
    
    Expected output
    2
    
  2. Example 2

    Input
    3
    1 2 3
    3 2 1
    0 0 0
    
    Expected output
    4
    
  3. Example 3

    Input
    4
    1 2 3 4
    4 3 2 1
    0 4 0 0
    
    Expected output
    3