Red-Black Tree

시간 제한3초메모리 제한512 MB

요약
가짜 검은 잎을 추가한 이진 트리에서 레드-블랙 성질을 만족하는 색칠의 수를 1e9+7로 나눈 나머지로 구한다.
난이도

보통10점 중 7점

유형
트리, 동적 계획법, DFS
정답자
아직 제출이 없습니다

문제

Did you now that most standard libraries use red-black tree to implement "set" data structure? In this problem you have to find the number of ways to color the vertices of the given binary tree so that it became red-black. Print the answer modulo 109 + 7.

Consider a binary tree. If the vertex has less than two children, add fake vertices to the potential places of the missing children. The tree is called a red-black tree if the following constraints are satisfied:

  1. Each vertex is colored one of the two colors: red or black.
  2. The root of the tree and added fake vertices are colored black.
  3. The parent of a red vertex is black.
  4. All paths the root to fake leafs contain the same number of black vertices.

Note that the parent of a black vertex can be black itself.

Two ways to color the tree are different if there is a vertex that has different colors.

The picture shows two ways to color the tree from the second test case.

입력

The first line contains one integer n — the number of vertices in a tree (1 ≤ n ≤ 500 000).

The following n lines describe a tree. The i-th of these lines contains two integers li and ri — the indices of the left and the right child of the i-th vertex, or 0 if the corresponding child is missing (li = 0 or i < li ≤ n; ri = 0 or i < ri ≤ n). The root of the tree has number 1. Input describes the correct tree.

출력

Output one integer — the number of ways to color the given tree so that it was a correct red-black tree. The answer must be printed modulo 109 + 7.

예제2

  1. 예제 1

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

    입력
    6
    2 4
    3 0
    0 0
    5 6
    0 0
    0 0
    
    예상 출력
    2