Problem:


Score : 600 points

Problem Statement

We have a tree with N vertices numbered 1 to N. The i-th edge in this tree connects Vertex a_i and b_i.
For each k=1, ..., N, solve the problem below:

Consider writing a number on each vertex in the tree in the following manner:

First, write 1 on Vertex k.

Then, for each of the numbers 2, ..., N in this order, write the number on the vertex chosen as follows:

Choose a vertex that still does not have a number written on it and is adjacent to a vertex with a number already written on it. If there are multiple such vertices, choose one of them at random.

Find the number of ways in which we can write the numbers on the vertices, modulo (10^9+7).

Constraints

2 \leq N \leq 2 \times 10^5

1 \leq a_i,b_i \leq N

The given graph is a tree.

Input

Input is given from Standard Input in the following format:

N
a_1 b_1
:
a_{N-1} b_{N-1}

Output

For each k=1, 2, ..., N in this order, print a line containing the answer to the problem.

Sample Input 1

3
1 2
1 3

Sample Output 1

2
1
1

The graph in this input is as follows:

For k=1, there are two ways in which we can write the numbers on the vertices, as follows:

Writing 1, 2, 3 on Vertex 1, 2, 3, respectively

Writing 1, 3, 2 on Vertex 1, 2, 3, respectively

Sample Input 2

2
1 2

Sample Output 2

1
1

The graph in this input is as follows:

Sample Input 3

5
1 2
2 3
3 4
3 5

Sample Output 3

2
8
12
3
3

The graph in this input is as follows:

Sample Input 4

8
1 2
2 3
3 4
3 5
3 6
6 7
6 8

Sample Output 4

40
280
840
120
120
504
72
72

The graph in this input is as follows:



Sample input:
3
1 2
1 3


Sample output:
2
1
1

Submission status: Time Limit Exceeded

Solution code:
import sys
from functools import lru_cache

sys.setrecursionlimit(1000000000)


def input(): return sys.stdin.readline().rstrip()


MOD = 10 ** 9 + 7


def memoize_fast(size):
    def decorator(f):
        memo = [-1] * size

        def wrapper(i):
            if memo[i] != -1:
                return memo[i]
            val = f(i)
            memo[i] = val
            return val

        return wrapper
    return decorator


@memoize_fast(2 * 10 ** 5)
def factorial(x):
    if x <= 1:
        return 1
    return x * factorial(x - 1) % MOD


@lru_cache(maxsize=None)
def inverse(x):
    return pow(x, MOD - 2, MOD)


@lru_cache(maxsize=None)
def combination(a, b):
    return factorial(a) * inverse(factorial(b)) % MOD * inverse(factorial(a - b)) % MOD


N = int(input())
graph = [[] for _ in range(N)]
for _ in range(N - 1):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    graph[a].append(b)
    graph[b].append(a)

children = [[] for _ in range(N)]
parent = [-1 for _ in range(N)]

visited = set()


def visit(node):
    visited.add(node)
    for n in graph[node]:
        if n not in visited:
            children[node].append(n)
            parent[n] = node
            visit(n)


visit(0)


@memoize_fast(2 * 10 ** 5)
def count(node):
    return 1 + sum(count(child) for child in children[node])


@memoize_fast(2 * 10 ** 5)
def order(node):
    ans = 1
    counts = []
    for child in children[node]:
        ans *= order(child)
        ans %= MOD
        counts.append(count(child))
    _sum = sum(counts)
    for c in counts:
        ans *= combination(_sum, c)
        ans %= MOD
        _sum -= c
    return ans


@memoize_fast(2 * 10 ** 5)
def order_all(node):
    if parent[node] == -1:
        return order(node)
    return order_all(parent[node]) * inverse(order(node)) % MOD * inverse(combination(N - 1, count(node))) % MOD * order(node) % MOD * combination(N - 1, count(node) - 1) % MOD


for node in range(N):
    print(order_all(node))

Submission status: Time Limit Exceeded

Solution code:
import sys
from functools import lru_cache
sys.setrecursionlimit(1000000000)


def input(): return sys.stdin.readline().rstrip()


MOD = 10 ** 9 + 7


def memoize_fast(size):
    def decorator(f):
        memo = [-1] * size

        def wrapper(i):
            if memo[i] != -1:
                return memo[i]
            val = f(i)
            memo[i] = val
            return val

        return wrapper
    return decorator


@memoize_fast(3 * 10 ** 5)
def factorial(x):
    if x <= 1:
        return 1
    return x * factorial(x - 1) % MOD


@lru_cache(maxsize=None)
def inverse(x):
    return pow(x, MOD - 2, MOD)


def combination(a, b):
    return factorial(a) * inverse(factorial(b)) % MOD * inverse(factorial(a - b)) % MOD


N = int(input())
graph = [[] for _ in range(N)]
for _ in range(N - 1):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    graph[a].append(b)
    graph[b].append(a)

children = [[] for _ in range(N)]
parent = [-1 for _ in range(N)]

visited = set()


def visit(node):
    visited.add(node)
    for n in graph[node]:
        if n not in visited:
            children[node].append(n)
            parent[n] = node
            visit(n)


visit(0)


@memoize_fast(3 * 10 ** 5)
def count(node):
    c = 1
    for child in children[node]:
        c += count(child)
    return c


@memoize_fast(3 * 10 ** 5)
def order(node):
    ans = 1
    counts = []
    for child in children[node]:
        ans *= order(child)
        ans %= MOD
        counts.append(count(child))
    _sum = sum(counts)
    while len(counts) > 0:
        ans *= combination(_sum, counts[-1])
        ans %= MOD
        _sum -= counts.pop()
    return ans


@memoize_fast(3 * 10 ** 5)
def order_all(node):
    if parent[node] == -1:
        return order(node)
    return order_all(parent[node]) * inverse(order(node)) % MOD * inverse(combination(N - 1, count(node))) % MOD * order(node) % MOD * combination(N - 1, count(node) - 1) % MOD


for node in range(N):
    print(order_all(node))

Submission status: Time Limit Exceeded

Solution code:
import sys
from functools import lru_cache
sys.setrecursionlimit(1000000000)


def input(): return sys.stdin.readline().rstrip()


MOD = 10 ** 9 + 7


def egcd(a, b):
    if a == 0:
        return b, 0, 1
    else:
        g, y, x = egcd(b % a, a)
        return g, x - (b // a) * y, y

def inverse(x):
    _, _, ans = egcd(MOD, x)
    return (ans % MOD + MOD) % MOD


def memoize_fast(size):
    def decorator(f):
        memo = [-1] * size

        def wrapper(i):
            if memo[i] != -1:
                return memo[i]
            val = f(i)
            memo[i] = val
            return val

        return wrapper
    return decorator


@memoize_fast(3 * 10 ** 5)
def factorial(x):
    if x <= 1:
        return 1
    return x * factorial(x - 1) % MOD


def combination(a, b):
    return factorial(a) * inverse(factorial(b)) % MOD * inverse(factorial(a - b)) % MOD


N = int(input())
graph = [[] for _ in range(N)]
for _ in range(N - 1):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    graph[a].append(b)
    graph[b].append(a)

children = [[] for _ in range(N)]
parent = [-1 for _ in range(N)]

visited = set()


def visit(node):
    visited.add(node)
    for n in graph[node]:
        if n not in visited:
            children[node].append(n)
            parent[n] = node
            visit(n)


visit(0)


@memoize_fast(3 * 10 ** 5)
def count(node):
    c = 1
    for child in children[node]:
        c += count(child)
    return c


@memoize_fast(3 * 10 ** 5)
def order(node):
    ans = 1
    counts = []
    for child in children[node]:
        ans *= order(child)
        ans %= MOD
        counts.append(count(child))
    _sum = sum(counts)
    while len(counts) > 0:
        ans *= combination(_sum, counts[-1])
        ans %= MOD
        _sum -= counts.pop()
    return ans


@memoize_fast(3 * 10 ** 5)
def order_all(node):
    if parent[node] == -1:
        return order(node)
    return order_all(parent[node]) * inverse(order(node)) % MOD * inverse(combination(N - 1, count(node))) % MOD * order(node) % MOD * combination(N - 1, count(node) - 1) % MOD


for node in range(N):
    print(order_all(node))

Submission status: Time Limit Exceeded

Solution code:
import sys
from functools import lru_cache
sys.setrecursionlimit(1000000000)


def input(): return sys.stdin.readline().rstrip()


MOD = 10 ** 9 + 7


def memoize_fast(size):
    def decorator(f):
        memo = [-1] * size

        def wrapper(i):
            if memo[i] != -1:
                return memo[i]
            val = f(i)
            memo[i] = val
            return val

        return wrapper
    return decorator


@memoize_fast(3 * 10 ** 5)
def factorial(x):
    if x <= 1:
        return 1
    return x * factorial(x - 1) % MOD

@lru_cache(maxsize=None)
def inverse(x):
    return pow(x, MOD - 2, MOD)


def combination(a, b):
    return factorial(a) * inverse(factorial(b)) % MOD * inverse(factorial(a - b)) % MOD


N = int(input())
graph = [[] for _ in range(N)]
for _ in range(N - 1):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    graph[a].append(b)
    graph[b].append(a)

children = [[] for _ in range(N)]
parent = [-1 for _ in range(N)]

visited = set()


def visit(node):
    visited.add(node)
    for n in graph[node]:
        if n not in visited:
            children[node].append(n)
            parent[n] = node
            visit(n)


visit(0)


@memoize_fast(3 * 10 ** 5)
def count(node):
    c = 1
    for child in children[node]:
        c += count(child)
    return c


@memoize_fast(3 * 10 ** 5)
def order(node):
    ans = 1
    counts = []
    for child in children[node]:
        ans *= order(child)
        ans %= MOD
        counts.append(count(child))
    _sum = sum(counts)
    while len(counts) > 0:
        ans *= combination(_sum, counts[-1])
        ans %= MOD
        _sum -= counts.pop()
    return ans


@memoize_fast(3 * 10 ** 5)
def order_all(node):
    if parent[node] == -1:
        return order(node)
    return order_all(parent[node]) * inverse(order(node)) % MOD * inverse(combination(N - 1, count(node))) % MOD * order(node) % MOD * combination(N - 1, count(node) - 1) % MOD


for node in range(N):
    print(order_all(node))

Submission status: Time Limit Exceeded

Solution code:
import sys
from functools import lru_cache
sys.setrecursionlimit(1000000000)


def input(): return sys.stdin.readline().rstrip()


MOD = 10 ** 9 + 7


def memoize_fast(size):
    def decorator(f):
        memo = [-1] * size

        def wrapper(i):
            if memo[i] != -1:
                return memo[i]
            val = f(i)
            memo[i] = val
            return val

        return wrapper
    return decorator


@memoize_fast(3 * 10 ** 5)
def factorial(x):
    if x <= 1:
        return 1
    return x * factorial(x - 1) % MOD

@lru_cache(maxsize=None)
def inverse(x):
    return pow(x, MOD - 2, MOD)


def combination(a, b):
    return factorial(a) * inverse(factorial(b)) % MOD * inverse(factorial(a - b)) % MOD


N = int(input())
graph = [[] for _ in range(N)]
for _ in range(N - 1):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    graph[a].append(b)
    graph[b].append(a)

children = [[] for _ in range(N)]
parent = [None for _ in range(N)]

visited = set()


def visit(node):
    visited.add(node)
    for n in graph[node]:
        if n not in visited:
            children[node].append(n)
            parent[n] = node
            visit(n)


visit(0)


@memoize_fast(3 * 10 ** 5)
def count(node):
    c = 1
    for child in children[node]:
        c += count(child)
    return c


@memoize_fast(3 * 10 ** 5)
def order(node):
    ans = 1
    counts = []
    for child in children[node]:
        ans *= order(child)
        ans %= MOD
        counts.append(count(child))
    _sum = sum(counts)
    while len(counts) > 0:
        ans *= combination(_sum, counts[-1])
        ans %= MOD
        _sum -= counts.pop()
    return ans


@memoize_fast(3 * 10 ** 5)
def order_all(node):
    if parent[node] is None:
        return order(node)
    return order_all(parent[node]) * inverse(order(node)) % MOD * inverse(combination(N - 1, count(node))) % MOD * order(node) % MOD * combination(N - 1, count(node) - 1) % MOD


for node in range(N):
    print(order_all(node))

Submission status: Time Limit Exceeded

Solution code:
import sys
from functools import lru_cache
sys.setrecursionlimit(1000000000)


def input(): return sys.stdin.readline().rstrip()


MOD = 10 ** 9 + 7


def memoize_fast(size):
    def decorator(f):
        memo = [-1] * size

        def wrapper(i):
            if memo[i] != -1:
                return memo[i]
            val = f(i)
            memo[i] = val
            return val

        return wrapper
    return decorator


@memoize_fast(3 * 10 ** 5)
def factorial(x):
    if x <= 1:
        return 1
    return x * factorial(x - 1) % MOD

@lru_cache(maxsize=None)
def inverse(x):
    return pow(x, MOD - 2, MOD)


def combination(a, b):
    return factorial(a) * inverse(factorial(b)) % MOD * inverse(factorial(a - b)) % MOD


N = int(input())
graph = [[] for _ in range(N)]
for _ in range(N - 1):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    graph[a].append(b)
    graph[b].append(a)

children = [[] for _ in range(N)]
parent = [None for _ in range(N)]

visited = set()


def visit(node):
    visited.add(node)
    for n in graph[node]:
        if n not in visited:
            children[node].append(n)
            parent[n] = node
            visit(n)


visit(0)


@memoize_fast(3 * 10 ** 5)
def count(node):
    c = 1
    for child in children[node]:
        c += count(child)
    return c


@memoize_fast(3 * 10 ** 5)
def order(node):
    ans = 1
    counts = []
    for child in children[node]:
        ans *= order(child)
        ans %= MOD
        counts.append(count(child))
    while len(counts) > 0:
        ans *= combination(sum(counts), counts[-1])
        ans %= MOD
        counts.pop()
    return ans


@memoize_fast(3 * 10 ** 5)
def order_all(node):
    if parent[node] is None:
        return order(node)
    return order_all(parent[node]) * inverse(order(node)) % MOD * inverse(combination(N - 1, count(node))) % MOD * order(node) % MOD * combination(N - 1, count(node) - 1) % MOD


for node in range(N):
    print(order_all(node))

Submission status: Time Limit Exceeded

Solution code:
import sys
from bisect import *
from heapq import *
from collections import *
from itertools import *
from functools import *

sys.setrecursionlimit(100000000)


def input(): return sys.stdin.readline().rstrip()


MOD = 10 ** 9 + 7


def memoize_fast(size):
    def decorator(f):
        memo = [None] * size

        def wrapper(i):
            if memo[i] is not None:
                return memo[i]
            val = f(i)
            memo[i] = val
            return val

        return wrapper
    return decorator


@memoize_fast(3 * 10 ** 5)
def factorial(x):
    if x <= 1:
        return 1
    return x * factorial(x - 1) % MOD


def inverse(x):
    return pow(x, MOD - 2, MOD)


def combination(a, b):
    return factorial(a) * inverse(factorial(b)) % MOD * inverse(factorial(a - b)) % MOD


N = int(input())
graph = [[] for _ in range(N)]
for _ in range(N - 1):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    graph[a].append(b)
    graph[b].append(a)

children = [[] for _ in range(N)]
parent = [None for _ in range(N)]

visited = set()


def visit(node):
    visited.add(node)
    for n in graph[node]:
        if n not in visited:
            children[node].append(n)
            parent[n] = node
            visit(n)


visit(0)


@memoize_fast(3 * 10 ** 5)
def count(node):
    c = 1
    for child in children[node]:
        c += count(child)
    return c


@memoize_fast(3 * 10 ** 5)
def order(node):
    ans = 1
    counts = []
    for child in children[node]:
        ans *= order(child)
        ans %= MOD
        counts.append(count(child))
    while len(counts) > 0:
        ans *= combination(sum(counts), counts[-1])
        ans %= MOD
        counts.pop()
    return ans


@memoize_fast(3 * 10 ** 5)
def order_all(node):
    if parent[node] is None:
        return order(node)
    return order_all(parent[node]) * inverse(order(node)) % MOD * inverse(combination(N - 1, count(node))) % MOD * order(node) % MOD * combination(N - 1, count(node) - 1) % MOD


for node in range(N):
    print(order_all(node))

Submission status: Time Limit Exceeded

Solution code:
import sys
from bisect import *
from heapq import *
from collections import *
from itertools import *
from functools import *

sys.setrecursionlimit(100000000)


def input(): return sys.stdin.readline().rstrip()


MOD = 10 ** 9 + 7


def memoize_fast(size):
    def decorator(f):
        memo = [None] * size

        def wrapper(i):
            if memo[i] is not None:
                return memo[i]
            val = f(i)
            memo[i] = val
            return val

        return wrapper
    return decorator


@memoize_fast(3 * 10 ** 5)
def factorial(x):
    if x <= 1:
        return 1
    return x * factorial(x - 1) % MOD


def inverse(x):
    return pow(x, MOD - 2, MOD)


def combination(a, b):
    return factorial(a) * inverse(factorial(b)) * inverse(factorial(a - b))


N = int(input())
graph = [[] for _ in range(N)]
for _ in range(N - 1):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    graph[a].append(b)
    graph[b].append(a)

children = [[] for _ in range(N)]
parent = [None for _ in range(N)]

visited = set()


def visit(node):
    visited.add(node)
    for n in graph[node]:
        if n not in visited:
            children[node].append(n)
            parent[n] = node
            visit(n)


visit(0)


@memoize_fast(3 * 10 ** 5)
def count(node):
    c = 1
    for child in children[node]:
        c += count(child)
    return c


@memoize_fast(3 * 10 ** 5)
def order(node):
    ans = 1
    counts = []
    for child in children[node]:
        ans *= order(child)
        ans %= MOD
        counts.append(count(child))
    while len(counts) > 0:
        ans *= combination(sum(counts), counts[-1])
        ans %= MOD
        counts.pop()
    return ans


@memoize_fast(3 * 10 ** 5)
def order_all(node):
    if parent[node] is None:
        return order(node)
    return order_all(parent[node]) * inverse(order(node)) % MOD * inverse(combination(N - 1, count(node))) % MOD * order(node) % MOD * combination(N - 1, count(node) - 1) % MOD


for node in range(N):
    print(order_all(node))

Submission status: Time Limit Exceeded

Solution code:
import sys
from bisect import *
from heapq import *
from collections import *
from itertools import *
from functools import *

sys.setrecursionlimit(100000000)


def input(): return sys.stdin.readline().rstrip()


MOD = 10 ** 9 + 7


@lru_cache(maxsize=None)
def factorial(x):
    if x <= 1:
        return 1
    return x * factorial(x - 1) % MOD


def inverse(x):
    return pow(x, MOD - 2, MOD)


def combination(a, b):
    return factorial(a) * inverse(factorial(b)) * inverse(factorial(a - b))


N = int(input())
graph = [[] for _ in range(N)]
for _ in range(N - 1):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    graph[a].append(b)
    graph[b].append(a)

children = [[] for _ in range(N)]
parent = [None for _ in range(N)]

visited = set()


def visit(node):
    visited.add(node)
    for n in graph[node]:
        if n not in visited:
            children[node].append(n)
            parent[n] = node
            visit(n)


visit(0)


@lru_cache(maxsize=None)
def count(node):
    c = 1
    for child in children[node]:
        c += count(child)
    return c


@lru_cache(maxsize=None)
def order(node):
    ans = 1
    counts = []
    for child in children[node]:
        ans *= order(child)
        ans %= MOD
        counts.append(count(child))
    while len(counts) > 0:
        ans *= combination(sum(counts), counts[-1])
        ans %= MOD
        counts.pop()
    return ans


@lru_cache(maxsize=None)
def order_all(node):
    if parent[node] is None:
        return order(node)
    return order_all(parent[node]) * inverse(order(node)) * inverse(combination(N - 1, count(node))) * order(node) * combination(N - 1, count(node) - 1) % MOD


for node in range(N):
    print(order_all(node))

Submission status: Time Limit Exceeded

Solution code:
import copy
n = int(input())
inp = []
for i in range (n-1):
    inp.append(list(map(int,input().split(" "))))

list_tree = [[] for i in range(n)]

for i in range(n-1):
    list_tree[inp[i][0]-1].append(inp[i][1]-1)
    list_tree[inp[i][1]-1].append(inp[i][0]-1)


fact_ = [1]
for i in range (1,n+1):
    fact_.append(fact_[i-1]*i%(10**9+7))
    


def ans(x,list1,fact):
    if list1[x]==[]:
        return [1,1]
    else:
        la = []
        for p in list1[x]:
            l = copy.deepcopy(list1)
            l[x].remove(p)
            l[p].remove(x)
            la.append(ans(p,l,fact))
        c = 1
        for i in range(len(la)):
            c = c+la[i][1]   
        a = fact[c-1]
        for i in range(len(la)):
            a = int(a*la[i][0]/fact[la[i][1]])%(10**9+7)
        return [a,c]
        
for i in range(n):
    print(ans(i,list_tree,fact_)[0])

Submission status: Time Limit Exceeded

Solution code:
class ReRooting(object):
    """ 全方位木DP """
    def processing(self, in_:list, v:int):
        """ 単項演算(加工) f """
        cnt = in_[0] * factinv[in_[1]] % MOD
        size = in_[1]
        return [cnt, size]
    
    def merge(self, in1:list, in2:list):
        """ 二項演算(マージ) ・ """
        cnt = in1[0] * in2[0] % MOD
        size = in1[1] + in2[1]
        return [cnt, size]

    def adjustment(self, in_:list, v:int):
        """ 単項演算(調整) g """
        cnt = in_[0] * fact[in_[1]] % MOD
        size = in_[1] + 1
        return [cnt, size]
    
    def solve(self):
        """
        計算結果を返す
        
        Ex. [cnt for cnt, _ in self.calc()]
        """
        return [cnt for cnt,_ in self.calc()]

    def __init__(self, V:int, e:list):
        """
        V: 頂点数
        e: 単位元
        """
        self.V, self.e = V, e
        self.edge = [[] for _ in range(V)]
        self.par = [-1] * V
        self.order = []
    
    def add_edge(self, u:int, v:int):
        """ 辺(u,v)をグラフに追加する """
        self.edge[u].append(v)
        self.edge[v].append(u)
    
    def topological_sort(self, root:int = 0):
        """ トポロジカルソート """
        from collections import deque
        que = deque([root])
        while que:
            v = que.popleft()
            self.order.append(v)
            for w in self.edge[v]:
                if w != self.par[v]:
                    self.par[w] = v
                    self.edge[w].remove(v)
                    que.append(w)
    
    def bottom_up(self):
        """ Bottom-Up DP """
        accBU = [self.e for _ in range(self.V)]
        resBU = [None] * self.V
        for v in reversed(self.order):
            for c in self.edge[v]:
                accBU[v] = self.merge(accBU[v], self.processing(resBU[c], c))
            resBU[v] = self.adjustment(accBU[v], v)
        return accBU, resBU
    
    def top_down(self, resBU:list):
        """ Top-Down DP """
        accTD = [self.e for _ in range(self.V)]
        resTD = [self.e for _ in range(self.V)]

        for p in self.order:
            ac = self.e if (p == self.order[0]) else self.processing(resTD[p], p)
            for v in self.edge[p]:
                accTD[v] = ac[:]
                ac = self.merge(ac, self.processing(resBU[v], v))
            
            ac = self.e
            for v in reversed(self.edge[p]):
                accTD[v] = self.merge(accTD[v], ac)
                resTD[v] = self.adjustment(accTD[v], v)
                ac = self.merge(ac, self.processing(resBU[v], v))
        return resTD
    
    def calc(self):
        self.topological_sort()
        accBU, resBU = self.bottom_up()
        resTD = self.top_down(resBU)

        res = [None] * self.V
        for v in self.order:
            res[v] = self.e if (v == self.order[0]) else self.processing(resTD[v], v)
            res[v] = self.merge(accBU[v], res[v])
            res[v] = self.adjustment(res[v], v)
        return res

#########################################################################################
N = int(input())
MOD = 10 ** 9 + 7
 
fact = [1] * (N + 1) # fact[n]: n!
factinv = [1] * (N + 1) # n!の逆元
for i in range(N):
    fact[i + 1] = fact[i] * (i + 1) % MOD
factinv[-1] = pow(fact[-1], MOD - 2, MOD)
for i in range(N - 1, -1, -1):
    factinv[i] = factinv[i + 1] * (i + 1) % MOD
 
def main():
    RR = ReRooting(N, [1, 0])
    for _ in range(N - 1):
        a, b = map(int, input().split())
        RR.add_edge(a - 1, b- 1)
    print(*RR.solve(), sep="\n")
 
 
if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
from functools import reduce

def extended_euclid(a, b):
    x1, y1, m = 1, 0, a
    x2, y2, n = 0, 1, b
    while m % n != 0:
        q, r = divmod(m, n)
        x1, y1, m, x2, y2, n = x2, y2, n, x1 - q * x2, y1 - q * y2, r
    return x2, y2, n

def modular_inverse(a, mod):
    x, _, g = extended_euclid(a, mod)
    if g != 1:
        return None # Modular inverse of a does not exist
    else:
        return x % mod

class Combinatorics:
    def __init__(self, N, mod):
        '''
        Preprocess for calculating binomial coefficients nCr (0 <= r <= n, 0 <= n <= N)
        over the finite field Z/(mod)Z.
        Input:
            N (int): maximum n
            mod (int): a prime number. The order of the field Z/(mod)Z over which nCr is calculated.
        '''
        self.mod = mod
        self.fact = [0] * (N+1)           # n!
        self.inverse = [None] + [0] * N   # inverse of n in the field Z/(MOD)Z
        self.fact_inverse = [0] * (N+1)   # inverse of n! in the field Z/(MOD)Z
        
        # preprocess
        self.fact[0] = self.fact[1] = 1
        self.fact_inverse[0] = self.fact_inverse[1] = 1
        self.inverse[1] = 1
        for i in range(2, N+1):
            self.fact[i] = i * self.fact[i-1] % self.mod
            q, r = divmod(self.mod, i)
            self.inverse[i] = (- (q % self.mod) * self.inverse[r]) % self.mod
            self.fact_inverse[i] = self.inverse[i] * self.fact_inverse[i-1] % self.mod
    
    def perm(self, n, r):
        '''
        Calculate nPr = n! / (n-r)! % mod
        '''
        if n < r or n < 0 or r < 0: return 0
        else: return (self.fact[n] * self.fact_inverse[n-r]) % self.mod
    
    def binom(self, n, r):
        '''
        Calculate nCr = n! /(r! (n-r)!) % mod
        '''
        if n < r or n < 0 or r < 0: return 0
        else: return self.fact[n] * (self.fact_inverse[r] * self.fact_inverse[n-r] % self.mod) % self.mod
        
    def multinom(self, R):
        '''
        Calculate \binom{sum(R)}{r1, ..., r_k}
        '''
        n = sum(R)
        return self.fact[n] * reduce(lambda x, y: self.fact_inverse[x] * self.fact_inverse[y] % self.mod, R) % self.mod
        
    def hom(self, n, r):
        '''
        Calculate nHr = {n+r-1}Cr % mod.
        Assign r objects to one of n classes.
        Arrangement of r circles and n-1 partitions:
            o o o | o o | | | o | | | o o | | o
        '''
        if n == 0 and r > 0: return 0
        if n >= 0 and r == 0: return 1
        return self.binom(n + r - 1, r)

MOD = 10**9 + 7
N = int(input())
com = Combinatorics(N, MOD)
T = [[] for _ in range(N)]
for _ in range(N-1):
    a, b = map(int, input().split())
    T[a-1].append(b-1); T[b-1].append(a-1)

# Consider T to be rooted at r = 0
downward = [1] * N
upward = [1] * N
n_descs = [1] * N
children_n_descs = [[] for _ in range(N)]
ans = [-1] * N

def dfs1(r):
    stack = [(r, -1, 0)] # (vertex, parent, status)
    while stack:
        v, p, st = stack.pop()
        if st == 0: # visited v for the first time
            n_children = 0
            for u in T[v]:
                if u == p: continue
                if n_children == 0:
                    stack += [(v, p, 2), (u, v, 0)]
                    n_children += 1
                else:
                    stack += [(v, p, 1), (u, v, 0)]
                    n_children += 1
            if n_children == 0: # v is a leaf
                stack += [(v, p, 2)]
        elif st == 1: # now searching
            continue
        else: # search finished
            n = n_descs[v]
            downward[v] = (downward[v] * com.fact[n-1]) % MOD
            if p != -1:
                n_descs[p] += n
                downward[p] = ((downward[p] * downward[v]) % MOD * com.fact_inverse[n]) % MOD

def dfs2(r):
    f_n1, f_n1_inv = com.fact[N-1], com.fact_inverse[N-1]
    stack = [(r, -1)] # (vertex, parent)
    while stack:
        v, p = stack.pop()
        n_v = n_descs[v]
        dw_v = downward[v]
        if p == -1: upward[v] = 1
        else: upward[v] = ans[p] * com.fact[N-1-n_v] % MOD * com.fact[n_v] % MOD * modular_inverse(dw_v, MOD) % MOD * f_n1_inv % MOD
        ans[v] = upward[v] * downward[v] % MOD * f_n1 % MOD * com.fact_inverse[N-n_v] % MOD * com.fact_inverse[n_v-1] % MOD
        for u in T[v]:
            if u == p: continue
            stack += [(u, v)]
dfs1(0)
dfs2(0)
for a in ans: print(a)