In-order

시간 제한1초메모리 제한1024 MB

요약
이진 트리의 전위 순회, 후위 순회, 그리고 중위 순회의 연속된 일부가 주어졌을 때, 가능한 서로 다른 중위 순회의 개수를 999,999,937로 나눈 나머지를 구한다.
난이도

어려움10점 중 8점

유형
트리, 분할 정복, 재귀, 조합론
정답자
아직 제출이 없습니다

문제

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 (conveniently 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, to make sure there are enough tree layouts so that each team can have a distinct one, you are asked to calculate the quantity of different possible in-order traversals, say TT, modulo the prime number 999,999,937999\\, 999\\, 937.

입력

The input consists of four lines. The first line contains the number NN. Each subsequent line contains a list of NN space-separated integers. The second line contains a list A_1,A_2,…,A_NA\_1, A\_2, \dots , A\_N, where A_kA\_k is the number of the kkth athlete found in pre-order traversal. The third line contains a list B_1,B_2,…,B_NB\_1, B\_2, \dots , B\_N, where B_kB\_k is the number of the kkth athlete found in post-order traversal. The fourth line contains a list C_1,C_2,…,C_NC\_1, C\_2, \dots , C\_N, where C_kC\_k is either the number of the kkth athlete found in in-order traversal, or 00 if the organiser did not say who that kkth athlete should be.

출력

The output should contain a single line, consisting of a single integer SS: this is the only integer such that 0≤S<999,999,9370 \le S < 999\\, 999\\, 937 and for which T−ST - S is divisible by 999,999,937999\\, 999\\, 937.

제한

  • 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 integers kk for which C_k≥1C\_k \ge 1 form a (possibly empty) sub-interval of the set 1,2,…,N\\{1, 2, \dots , N\\}; in other words, whenever k≤ℓk \le \ell and both C_kC\_k and C_ℓC\_\ell are positive, all the integers C_k,C_k+1,…,C_ℓC\_k , C\_{k+1} , \dots , C\_\ell are positive.

예제3

  1. 예제 1

    입력
    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
    
    예상 출력
    2
    
  2. 예제 2

    입력
    3
    1 2 3
    3 2 1
    0 0 0
    
    예상 출력
    4
    
  3. 예제 3

    입력
    4
    1 2 3 4
    4 3 2 1
    0 4 0 0
    
    예상 출력
    3