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
sys.setrecursionlimit(10**9)
input = sys.stdin.readline

MOD = 10**9 + 7
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)

MAX = n + 5
fact = [1] * (MAX + 1)  # i!
finv = [1] * (MAX + 1)  # (i!)^{-1}
iinv = [1] * (MAX + 1)  # i^{-1}
for i in range(2, MAX + 1):
    fact[i] = fact[i - 1] * i % MOD
    iinv[i] = MOD - iinv[MOD % i] * (MOD // i) % MOD
    finv[i] = finv[i - 1] * iinv[i] % MOD

ele_id = (1, 0)
# dp[v][i] = (頂点vから出るi番目の有向辺に関する部分木のDPの値)
# dp[v][i] = (c, m)
# c = 頂点vから出るi番目の有向辺に関する部分木の塗り方の数
# m = 頂点vから出るi番目の有向辺に関する部分木の頂点数
dp = [[ele_id] * len(graph[i]) for i in range(n)]
ans = [ele_id] * n

add_func = lambda x: (x[0], x[1] + 1)


def merge_func(a, b):
    m = a[1] + b[1]
    dp_a = a[0] * finv[a[1]] % MOD
    dp_b = b[0] * finv[b[1]] % MOD
    c = (dp_a * dp_b % MOD) * fact[m] % MOD
    return (c, m)


def dfs1(v, v_p):
    dp_cum = ele_id
    for i, v_next in enumerate(graph[v]):
        if v_next == v_p:
            continue
        dp[v][i] = dfs1(v_next, v)
        dp_cum = merge_func(dp_cum, dp[v][i])
    return add_func(dp_cum)


def dfs2(v, v_p, dp_vp):
    for i, v_next in enumerate(graph[v]):
        if v_next == v_p:
            dp[v][i] = dp_vp
            break

    dp_l = [ele_id] * (len(graph[v]) + 1)
    dp_r = [ele_id] * (len(graph[v]) + 1)
    for i in range(len(graph[v])):
        dp_l[i + 1] = merge_func(dp_l[i], dp[v][i])
    for i in reversed(range(len(graph[v]))):
        dp_r[i] = merge_func(dp_r[i + 1], dp[v][i])

    ans[v] = add_func(dp_l[-1])

    for i, v_next in enumerate(graph[v]):
        if v_next == v_p:
            continue
        dfs2(v_next, v, add_func(merge_func(dp_l[i], dp_r[i + 1])))


dfs1(0, -1)
dfs2(0, -1, ele_id)
for ans_i, _ in ans:
    print(ans_i)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**9)

MOD = 10**9 + 7
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)

MAX = n + 5
fact = [1] * (MAX + 1)  # i!
finv = [1] * (MAX + 1)  # (i!)^{-1}
iinv = [1] * (MAX + 1)  # i^{-1}
for i in range(2, MAX + 1):
    fact[i] = fact[i - 1] * i % MOD
    iinv[i] = MOD - iinv[MOD % i] * (MOD // i) % MOD
    finv[i] = finv[i - 1] * iinv[i] % MOD

ele_id = (1, 0)
# dp[v][i] = (頂点vから出るi番目の有向辺に関する部分木のDPの値)
# dp[v][i] = (c, m)
# c = 頂点vから出るi番目の有向辺に関する部分木の塗り方の数
# m = 頂点vから出るi番目の有向辺に関する部分木の頂点数
dp = [[ele_id] * len(graph[i]) for i in range(n)]
ans = [ele_id] * n

add_func = lambda x: (x[0], x[1] + 1)


def merge_func(a, b):
    m = a[1] + b[1]
    dp_a = a[0] * finv[a[1]] % MOD
    dp_b = b[0] * finv[b[1]] % MOD
    c = (dp_a * dp_b % MOD) * fact[m] % MOD
    return (c, m)


def dfs1(v, v_p):
    dp_cum = ele_id
    for i, v_next in enumerate(graph[v]):
        if v_next == v_p:
            continue
        dp[v][i] = dfs1(v_next, v)
        dp_cum = merge_func(dp_cum, dp[v][i])
    return add_func(dp_cum)


def dfs2(v, v_p, dp_vp):
    for i, v_next in enumerate(graph[v]):
        if v_next == v_p:
            dp[v][i] = dp_vp

    dp_l = [ele_id] * (len(graph[v]) + 1)
    dp_r = [ele_id] * (len(graph[v]) + 1)
    for i in range(len(graph[v])):
        dp_l[i + 1] = merge_func(dp_l[i], dp[v][i])
    for i in reversed(range(len(graph[v]))):
        dp_r[i] = merge_func(dp_r[i + 1], dp[v][i])

    ans[v] = add_func(dp_l[-1])

    for i, v_next in enumerate(graph[v]):
        if v_next == v_p:
            continue
        dfs2(v_next, v, add_func(merge_func(dp_l[i], dp_r[i + 1])))


dfs1(0, -1)
dfs2(0, -1, ele_id)
for ans_i, _ in ans:
    print(ans_i)

Submission status: Time Limit Exceeded

Solution code:
#!python3

import sys
sys.setrecursionlimit(10 ** 6)

MOD = 10 ** 9 + 7


class ModInt:
    def __init__(self, x):
        self.x = x % MOD

    def __str__(self):
        return str(self.x)

    __repr__ = __str__

    def __add__(self, other):
        return (
            ModInt(self.x + other.x) if isinstance(other, ModInt) else
            ModInt(self.x + other)
        )

    def __sub__(self, other):
        return (
            ModInt(self.x - other.x) if isinstance(other, ModInt) else
            ModInt(self.x - other)
        )

    def __mul__(self, other):
        return (
            ModInt(self.x * other.x) if isinstance(other, ModInt) else
            ModInt(self.x * other)
        )

    def __truediv__(self, other):
        return (
            ModInt(
                self.x * pow(other.x, MOD - 2, MOD)
            ) if isinstance(other, ModInt) else
            ModInt(self.x * pow(other, MOD - 2, MOD))
        )

    def __pow__(self, other):
        return (
            ModInt(pow(self.x, other.x, MOD)) if isinstance(other, ModInt) else
            ModInt(pow(self.x, other, MOD))
        )

    __radd__ = __add__

    def __rsub__(self, other):
        return (
            ModInt(other.x - self.x) if isinstance(other, ModInt) else
            ModInt(other - self.x)
        )

    __rmul__ = __mul__

    def __rtruediv__(self, other):
        return (
            ModInt(
                other.x * pow(self.x, MOD - 2, MOD)
            ) if isinstance(other, ModInt) else
            ModInt(other * pow(self.x, MOD - 2, MOD))
        )

    def __rpow__(self, other):
        return (
            ModInt(pow(other.x, self.x, MOD)) if isinstance(other, ModInt) else
            ModInt(pow(other, self.x, MOD))
        )


LI = lambda: list(map(int, input().split()))

# input
N = int(input())
AB = [LI() for _ in range(N - 1)]

# params
links = [[] for i in range(N)]
dp = [ModInt(1) for _ in range(N)]
c = [1] * N

MAX = 2 * (10 ** 5) + 5
fac, finv, inv = [None] * MAX, [None] * MAX, [None] * MAX


def comb_init():
    fac[0] = fac[1] = 1
    finv[0] = finv[1] = 1
    inv[1] = 1
    for i in range(2, MAX):
        fac[i] = fac[i - 1] * i % MOD
        inv[i] = -inv[MOD%i] * int(MOD / i) % MOD
        finv[i] = finv[i - 1] * inv[i] % MOD


def comb(n, k):
    if n < k or n < 0 or k < 0:
        return 0
    return fac[n] * (finv[k] * finv[n - k] % MOD) % MOD


def create_links():
    for a, b in AB:
        links[a - 1].append(b - 1)
        links[b - 1].append(a - 1)
    return links


def dfs1(v, p=-1):
    for u in links[v]:
        if u == p:
            continue
        dfs1(u, v)
        c[v] += c[u]
        dp[v] *= dp[u]
        dp[v] *= finv[c[u]]
    dp[v] *= fac[c[v] - 1]


def dfs2(v, p=-1):
    for u in links[v]:
        if u == p:
            continue
        dp[u] = dp[v] * c[u] * inv[(N - c[u])]
        dfs2(u, v)


def main():
    comb_init()
    create_links()
    dfs1(0)
    dfs2(0)
    [print(ans) for ans in dp]


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
#!python3

import sys
sys.setrecursionlimit(10 ** 6)

MOD = 10 ** 9 + 7


class ModInt:
    def __init__(self, x):
        self.x = x % MOD

    def __str__(self):
        return str(self.x)

    __repr__ = __str__

    def __add__(self, other):
        return (
            ModInt(self.x + other.x) if isinstance(other, ModInt) else
            ModInt(self.x + other)
        )

    def __sub__(self, other):
        return (
            ModInt(self.x - other.x) if isinstance(other, ModInt) else
            ModInt(self.x - other)
        )

    def __mul__(self, other):
        return (
            ModInt(self.x * other.x) if isinstance(other, ModInt) else
            ModInt(self.x * other)
        )

    def __truediv__(self, other):
        return (
            ModInt(
                self.x * pow(other.x, MOD - 2, MOD)
            ) if isinstance(other, ModInt) else
            ModInt(self.x * pow(other, MOD - 2, MOD))
        )

    def __pow__(self, other):
        return (
            ModInt(pow(self.x, other.x, MOD)) if isinstance(other, ModInt) else
            ModInt(pow(self.x, other, MOD))
        )

    __radd__ = __add__

    def __rsub__(self, other):
        return (
            ModInt(other.x - self.x) if isinstance(other, ModInt) else
            ModInt(other - self.x)
        )

    __rmul__ = __mul__

    def __rtruediv__(self, other):
        return (
            ModInt(
                other.x * pow(self.x, MOD - 2, MOD)
            ) if isinstance(other, ModInt) else
            ModInt(other * pow(self.x, MOD - 2, MOD))
        )

    def __rpow__(self, other):
        return (
            ModInt(pow(other.x, self.x, MOD)) if isinstance(other, ModInt) else
            ModInt(pow(other, self.x, MOD))
        )


LI = lambda: list(map(int, input().split()))

# input
N = int(input())
AB = [LI() for _ in range(N - 1)]

# params
links = [[] for i in range(N)]
dp = [ModInt(1) for _ in range(N)]
c = [1] * N

MAX = 2 * (10 ** 5) + 5
fac, finv, inv = [None] * MAX, [None] * MAX, [None] * MAX


def comb_init():
    fac[0] = fac[1] = 1
    finv[0] = finv[1] = 1
    inv[1] = 1
    for i in range(2, MAX):
        fac[i] = fac[i - 1] * i % MOD
        inv[i] = -inv[MOD%i] * int(MOD / i) % MOD
        finv[i] = finv[i - 1] * inv[i] % MOD


def comb(n, k):
    if n < k or n < 0 or k < 0:
        return 0
    return fac[n] * (finv[k] * finv[n - k] % MOD) % MOD


def create_links():
    for a, b in AB:
        links[a - 1].append(b - 1)
        links[b - 1].append(a - 1)
    return links


def dfs1(v, p=-1):
    for u in links[v]:
        if u == p:
            continue
        dfs1(u, v)
        c[v] += c[u]
        dp[v] *= dp[u]
        dp[v] /= fac[c[u]]
    dp[v] *= fac[c[v] - 1]


def dfs2(v, p=-1):
    for u in links[v]:
        if u == p:
            continue
        dp[u] = dp[v] * c[u] / (N - c[u])
        dfs2(u, v)


def main():
    comb_init()
    create_links()
    dfs1(0)
    dfs2(0)
    [print(ans) for ans in dp]


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
ab=[list(map(int,input().split())) for _ in range(n-1)]
mod=pow(10,9)+7
ki=[[] for _ in range(n)]
todo=[]
for a,b in ab:
  ki[a-1].append(b-1)
  ki[b-1].append(a-1)
import sys
sys.setrecursionlimit(100000)
def cmb(n, r, mod):
    if ( r<0 or r>n ):
        return 0
    r = min(r, n-r)
    return g1[n] * g2[r] * g2[n-r] % mod
g1 = [1, 1] 
g2 = [1, 1] 
inverse = [0, 1]
for i in range( 2, n + 1 ):
    g1.append( ( g1[-1] * i ) % mod )
    inverse.append( ( -inverse[mod % i] * (mod//i) ) % mod )
    g2.append( (g2[-1] * inverse[-1]) % mod )
memo={}
def dfs(i,pare):#根がi、親がpareの部分木についての値を返す。[サイズ,整数の書き方の場合の数]
  if (i,pare) in memo:
    return memo[(i,pare)]
  l=ki[i]
  ret=0
  sizes=[]
  pats=[]
  sum_size=0
  ret=1
  for li in l:
    if li==pare:
      continue
    size,pat=dfs(li,i)
    sizes.append(size)
    sum_size+=size
    ret*=cmb(sum_size,size,mod)
    ret*=pat
  memo[(i,pare)]=(sum_size+1,ret)
  return (sum_size+1,ret)
for i in range(n):
  print(dfs(i,-1)[1])

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
ab=[list(map(int,input().split())) for _ in range(n-1)]
mod=pow(10,9)+7
ki=[[] for _ in range(n)]
todo=[]
for a,b in ab:
  ki[a-1].append(b-1)
  ki[b-1].append(a-1)
  todo.append((a-1,b-1))
  todo.append((b-1,a-1))
import sys
sys.setrecursionlimit(100000)
nCr = {}
def cmb(n, r):
    if r == 0 or r == n: return 1
    if r == 1: return n
    if (n,r) in nCr: return nCr[(n,r)]
    nCr[(n,r)] = cmb(n-1,r) + cmb(n-1,r-1)
    return nCr[(n,r)]%mod

dp={}
def node(i,j):
  if (i,j) in dp:
    return dp[(i,j)]
  l=ki[j]
  pat,size=1,0
  for li in l:
    if li!=i:
      if (j,li) in dp:
        sizei,pati=dp[(j,li)]
      else:
        sizei,pati=node(j,li)
        dp[(j,li)]=(sizei,pati)
      size+=sizei
      pat*=cmb(size,sizei)
      pat*=pati
      pat%=mod
  return size+1,pat
while len(dp)<2*(n-1):
    t=todo.pop()
    if t not in dp:
        size,pat=node(t[0],t[1])
        dp[t]=size,pat

for i in range(n):
  l=ki[i]
  size=0
  pat=1
  for li in l:
    sizei,pati=dp[(i,li)]
    size+=sizei
    pat*=cmb(size,sizei)
    pat*=pati
    pat%=mod
  print(pat)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Fri May  8 12:10:59 2020
 
@author: ybt07
"""
 
import sys
sys.setrecursionlimit(3*10**5)  # 繰り返し制限
 
# 組み合わせ
N = 2*10**5   # 問題サイズに合わせて変えておく
MOD = 10**9 + 7
 
# 入力高速化
input = lambda : sys.stdin.readline().rstrip()
 
# modint
# https://qiita.com/wotsushi/items/c936838df992b706084c
 
class ModInt:
    def __init__(self, x):
        self.x = x % MOD
 
    def __str__(self):
        return str(self.x)
 
    __repr__ = __str__
 
    def __add__(self, other):
        return (
            ModInt(self.x + other.x) if isinstance(other, ModInt) else
            ModInt(self.x + other)
        )
 
    def __sub__(self, other):
        return (
            ModInt(self.x - other.x) if isinstance(other, ModInt) else
            ModInt(self.x - other)
        )
 
    def __mul__(self, other):
        return (
            ModInt(self.x * other.x) if isinstance(other, ModInt) else
            ModInt(self.x * other)
        )
 
    # / : 商。　逆元はフェルマーの小定理を利用している
    def __truediv__(self, other):
        return (
            ModInt(
                self.x * inv[other.x]
            ) if isinstance(other, ModInt) else
            ModInt(self.x * inv[other])
        )
 
    # ** : 指数
    def __pow__(self, other):
        return (
            ModInt(pow(self.x, other.x, MOD)) if isinstance(other, ModInt) else
            ModInt(pow(self.x, other, MOD))
        )
 
    # x が Modint、y が通常の int の場合に、y.__add__(x) に対して、何を適用するか、定義している（→ x.__add__(y)を呼べ） 
    __radd__ = __add__
 
    def __rsub__(self, other):
        return (
            ModInt(other.x - self.x) if isinstance(other, ModInt) else
            ModInt(other - self.x)
        )
 
    __rmul__ = __mul__
 
    def __rtruediv__(self, other):
        return (
            ModInt(
                other.x * inv[self.x]
            ) if isinstance(other, ModInt) else
            ModInt(other * inv[self.x])
        )
 
    def __rpow__(self, other):
        return (
            ModInt(pow(other.x, self.x, MOD)) if isinstance(other, ModInt) else
            ModInt(pow(other, self.x, MOD))
        )
 
def cmb(n, r):
    if ( r<0 or r>n ):
        return 0
    r = min(r, n-r)
    return fac[n] * facinv[r] * facinv[n-r] % MOD
 
fac = [1, 1] # 元テーブル
facinv = [1, 1] # 逆元テーブル
inv = [0, 1] # 逆元テーブル計算用テーブル
 
for i in range(2, N):
    fac.append( ( fac[-1] * i ) % MOD )
    inv.append( ( -inv[MOD % i] * (MOD//i) ) % MOD )
    facinv.append( (facinv[-1] * inv[-1]) % MOD )
 
# 部分木のDP値を求めていく
# u : 求める頂点
# 親（親側に辿らないように） p
 
def dfs(u, p = -1):
 
    global DP, CN, E
    
    # tmp_ans = 1
    # tmp_cn = 0  # （自分を含む）部分木のノード数
 
    # u から出ている頂点 v
    for v in E[u]:
        if not v == p:  # 親への辺以外について
            DP[v], CN[v] = dfs(v, u)
            CN[u] += CN[v]
            DP[u] *= DP[v] * cmb(CN[u], CN[v])
    CN[u] += 1
            
    return DP[u], CN[u]
 
# 各頂点の真のDP値を求めていく
 
def bfs(u, p=-1):
    
    global DP, E
        
    for v in E[u]:  # 各vに対して「真のDP値」を求めていく
        if v == p:
            continue
            
        # DP[u] と DP[v] から DP[v <- u] を求める
        cnv = CN[v]
        tmp_cn = N - cnv  # v から見たときの u の部分木の要素数
        DP[v] = DP[u] * cnv / tmp_cn 
 
        bfs(v, u)
    
    return
 
# 入力処理
N = int(input())  # 頂点数

from collections import defaultdict
E = defaultdict(set)  # 辺の情報
 
for _ in range(N - 1):
    a, b = map(int, input().split())
    E[a-1].add(b-1)  # 双方向の情報
    E[b-1].add(a-1)
    
DP = [ModInt(1)] * N
CN = [0] * N
 
dfs(0)
bfs(0)
 
print(*DP, sep="\n")

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Fri May  8 12:10:59 2020

@author: ybt07
"""

import sys
sys.setrecursionlimit(3*10**5)  # 繰り返し制限

# 組み合わせ
N = 2*10**5   # 問題サイズに合わせて変えておく
MOD = 10**9 + 7

# 入力高速化
input = lambda : sys.stdin.readline().rstrip()

# modint
# https://qiita.com/wotsushi/items/c936838df992b706084c

class ModInt:
    def __init__(self, x):
        self.x = x % MOD

    def __str__(self):
        return str(self.x)

    __repr__ = __str__

    def __add__(self, other):
        return (
            ModInt(self.x + other.x) if isinstance(other, ModInt) else
            ModInt(self.x + other)
        )

    def __sub__(self, other):
        return (
            ModInt(self.x - other.x) if isinstance(other, ModInt) else
            ModInt(self.x - other)
        )

    def __mul__(self, other):
        return (
            ModInt(self.x * other.x) if isinstance(other, ModInt) else
            ModInt(self.x * other)
        )

    # / : 商。　逆元はフェルマーの小定理を利用している
    def __truediv__(self, other):
        return (
            ModInt(
                self.x * inv[other.x]
            ) if isinstance(other, ModInt) else
            ModInt(self.x * inv[other])
        )

    # ** : 指数
    def __pow__(self, other):
        return (
            ModInt(pow(self.x, other.x, MOD)) if isinstance(other, ModInt) else
            ModInt(pow(self.x, other, MOD))
        )

    # x が Modint、y が通常の int の場合に、y.__add__(x) に対して、何を適用するか、定義している（→ x.__add__(y)を呼べ） 
    __radd__ = __add__

    def __rsub__(self, other):
        return (
            ModInt(other.x - self.x) if isinstance(other, ModInt) else
            ModInt(other - self.x)
        )

    __rmul__ = __mul__

    def __rtruediv__(self, other):
        return (
            ModInt(
                other.x * inv[self.x]
            ) if isinstance(other, ModInt) else
            ModInt(other * inv[self.x])
        )

    def __rpow__(self, other):
        return (
            ModInt(pow(other.x, self.x, MOD)) if isinstance(other, ModInt) else
            ModInt(pow(other, self.x, MOD))
        )

def cmb(n, r):
    if ( r<0 or r>n ):
        return 0
    r = min(r, n-r)
    return fac[n] * facinv[r] * facinv[n-r] % MOD

fac = [1, 1] # 元テーブル
facinv = [1, 1] # 逆元テーブル
inv = [0, 1] # 逆元テーブル計算用テーブル

for i in range(2, N):
    fac.append( ( fac[-1] * i ) % MOD )
    inv.append( ( -inv[MOD % i] * (MOD//i) ) % MOD )
    facinv.append( (facinv[-1] * inv[-1]) % MOD )

# 部分木のDP値を求めていく
# u : 求める頂点
# 親（親側に辿らないように） p

def dfs(u, p = -1):

    global DP, CN, E
    
    # tmp_ans = 1
    # tmp_cn = 0  # （自分を含む）部分木のノード数

    # u から出ている頂点 v
    for v in E[u]:
        if not v == p:  # 親への辺以外について
            DP[v], CN[v] = dfs(v, u)
            CN[u] += CN[v]
            DP[u] *= DP[v] * cmb(CN[u], CN[v])
    CN[u] += 1
            
    return DP[u], CN[u]

# 各頂点の真のDP値を求めていく

def bfs(u, p=-1):
    
    global DP, E
        
    for v in E[u]:  # 各vに対して「真のDP値」を求めていく
        if v == p:
            continue
            
        # DP[u] と DP[v] から DP[v <- u] を求める
        cnv = CN[v]
        tmp_cn = N - cnv  # v から見たときの u の部分木の要素数
        DP[v] = DP[u] * cnv / tmp_cn 

        bfs(v, u)
    
    return

# 入力処理
N = int(input())  # 頂点数
E = [[] for _ in range(N)]  # 辺の情報

for _ in range(N - 1):
    a, b = map(int, input().split())
    E[a-1].append(b-1)  # 双方向の情報
    E[b-1].append(a-1)
    
DP = [ModInt(1)] * N
CN = [0] * N

dfs(0)
bfs(0)

print(*DP, sep="\n")

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Fri May  8 12:10:59 2020

@author: ybt07
"""

import sys
import time
sys.setrecursionlimit(3*10**5)  # 繰り返し制限

# 組み合わせ
N = 2*10**5   # 問題サイズに合わせて変えておく
MOD = 10**9 + 7

# modint
# https://qiita.com/wotsushi/items/c936838df992b706084c

class ModInt:
    def __init__(self, x):
        self.x = x % MOD

    def __str__(self):
        return str(self.x)

    __repr__ = __str__

    def __add__(self, other):
        return (
            ModInt(self.x + other.x) if isinstance(other, ModInt) else
            ModInt(self.x + other)
        )

    def __sub__(self, other):
        return (
            ModInt(self.x - other.x) if isinstance(other, ModInt) else
            ModInt(self.x - other)
        )

    def __mul__(self, other):
        return (
            ModInt(self.x * other.x) if isinstance(other, ModInt) else
            ModInt(self.x * other)
        )

    # / : 商。　逆元はフェルマーの小定理を利用している
    def __truediv__(self, other):
        return (
            ModInt(
                self.x * inv[other.x]
            ) if isinstance(other, ModInt) else
            ModInt(self.x * inv[other])
        )

    # ** : 指数
    def __pow__(self, other):
        return (
            ModInt(pow(self.x, other.x, MOD)) if isinstance(other, ModInt) else
            ModInt(pow(self.x, other, MOD))
        )

    # x が Modint、y が通常の int の場合に、y.__add__(x) に対して、何を適用するか、定義している（→ x.__add__(y)を呼べ） 
    __radd__ = __add__

    def __rsub__(self, other):
        return (
            ModInt(other.x - self.x) if isinstance(other, ModInt) else
            ModInt(other - self.x)
        )

    __rmul__ = __mul__

    def __rtruediv__(self, other):
        return (
            ModInt(
                other.x * inv[self.x]
            ) if isinstance(other, ModInt) else
            ModInt(other * inv[self.x])
        )

    def __rpow__(self, other):
        return (
            ModInt(pow(other.x, self.x, MOD)) if isinstance(other, ModInt) else
            ModInt(pow(other, self.x, MOD))
        )

def cmb(n, r):
    if ( r<0 or r>n ):
        return 0
    r = min(r, n-r)
    return fac[n] * facinv[r] * facinv[n-r] % MOD

fac = [1, 1] # 元テーブル
facinv = [1, 1] # 逆元テーブル
inv = [0, 1] # 逆元テーブル計算用テーブル

for i in range(2, N):
    fac.append( ( fac[-1] * i ) % MOD )
    inv.append( ( -inv[MOD % i] * (MOD//i) ) % MOD )
    facinv.append( (facinv[-1] * inv[-1]) % MOD )

# 部分木のDP値を求めていく
# u : 求める頂点
# 親（親側に辿らないように） p

def dfs(u, p = -1):

    global DP, CN, E
    
    # tmp_ans = 1
    # tmp_cn = 0  # （自分を含む）部分木のノード数

    # u から出ている頂点 v
    for v in E[u]:
        if not v == p:  # 親への辺以外について
            DP[v], CN[v] = dfs(v, u)
            CN[u] += CN[v]
            DP[u] *= DP[v] * cmb(CN[u], CN[v])
    CN[u] += 1
            
    return DP[u], CN[u]

# 各頂点の真のDP値を求めていく

def bfs(u, p=-1):
    
    global DP, E
        
    for v in E[u]:  # 各vに対して「真のDP値」を求めていく
        if v == p:
            continue
            
        # DP[u] と DP[v] から DP[v <- u] を求める
        cnv = CN[v]
        tmp_cn = N - cnv  # v から見たときの u の部分木の要素数
        DP[v] = DP[u] * cnv / tmp_cn 

        bfs(v, u)
    
    return

# 入力処理
N = int(input())  # 頂点数
E = [[] for _ in range(N)]  # 辺の情報

for _ in range(N - 1):
    a, b = map(int, input().split())
    E[a-1].append(b-1)  # 双方向の情報
    E[b-1].append(a-1)
    
DP = [ModInt(1)] * N
CN = [0] * N

dfs(0)
bfs(0)

print(*DP, sep="\n")

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Fri May  8 12:10:59 2020

@author: ybt07
"""

import sys
import time
sys.setrecursionlimit(3*10**5)  # 繰り返し制限

# 組み合わせ
N = 2*10**5   # 問題サイズに合わせて変えておく
MOD = 10**9 + 7

# modint
# https://qiita.com/wotsushi/items/c936838df992b706084c

class ModInt:
    def __init__(self, x):
        self.x = x % MOD

    def __str__(self):
        return str(self.x)

    __repr__ = __str__

    def __add__(self, other):
        return (
            ModInt(self.x + other.x) if isinstance(other, ModInt) else
            ModInt(self.x + other)
        )

    def __sub__(self, other):
        return (
            ModInt(self.x - other.x) if isinstance(other, ModInt) else
            ModInt(self.x - other)
        )

    def __mul__(self, other):
        return (
            ModInt(self.x * other.x) if isinstance(other, ModInt) else
            ModInt(self.x * other)
        )

    # / : 商。　逆元はフェルマーの小定理を利用している
    def __truediv__(self, other):
        return (
            ModInt(
                self.x * inv[other.x]
            ) if isinstance(other, ModInt) else
            ModInt(self.x * inv[other])
        )

    # ** : 指数
    def __pow__(self, other):
        return (
            ModInt(pow(self.x, other.x, MOD)) if isinstance(other, ModInt) else
            ModInt(pow(self.x, other, MOD))
        )

    # x が Modint、y が通常の int の場合に、y.__add__(x) に対して、何を適用するか、定義している（→ x.__add__(y)を呼べ） 
    __radd__ = __add__

    def __rsub__(self, other):
        return (
            ModInt(other.x - self.x) if isinstance(other, ModInt) else
            ModInt(other - self.x)
        )

    __rmul__ = __mul__

    def __rtruediv__(self, other):
        return (
            ModInt(
                other.x * pow(self.x, MOD - 2, MOD)
            ) if isinstance(other, ModInt) else
            ModInt(other * pow(self.x, MOD - 2, MOD))
        )

    def __rpow__(self, other):
        return (
            ModInt(pow(other.x, self.x, MOD)) if isinstance(other, ModInt) else
            ModInt(pow(other, self.x, MOD))
        )

def cmb(n, r):
    if ( r<0 or r>n ):
        return 0
    r = min(r, n-r)
    return ModInt(fac[n] * facinv[r] * facinv[n-r])

fac = [1, 1] # 元テーブル
facinv = [1, 1] #逆元テーブル
inv = [0, 1] #逆元テーブル計算用テーブル

for i in range(2, N):
    fac.append( ( fac[-1] * i ) % MOD )
    inv.append( ( -inv[MOD % i] * (MOD//i) ) % MOD )
    facinv.append( (facinv[-1] * inv[-1]) % MOD )

# 部分木のDP値を求めていく
# u : 求める頂点
# 親（親側に辿らないように） p

def dfs(u, p = -1):

    global DP, CN, E
    
    # tmp_ans = 1
    # tmp_cn = 0  # （自分を含む）部分木のノード数

    # u から出ている頂点 v
    for v in E[u]:
        if v != p:  # 親への辺以外について
            DP[v], CN[v] = dfs(v, u)
            CN[u] += CN[v]
            DP[u] *= DP[v] * cmb(CN[u], CN[v])
    CN[u] += 1
            
    return DP[u], CN[u]

# 各頂点の真のDP値を求めていく

def bfs(u, p=-1):
    
    global DP, E
        
    for v in E[u]:  # 各vに対して「真のDP値」を求めていく
        if v == p:
            continue
            
        # DP[u] と DP[v] から DP[v <- u] を求める
        cnv = CN[v]
        tmp_cn = N - cnv  # v から見たときの u の部分木の要素数
        DP[v] = DP[u] * cnv / tmp_cn 

        bfs(v, u)
    
    return

# 入力処理
N = int(input())  # 頂点数
E = [[] for _ in range(N)]  # 辺の情報

for _ in range(N - 1):
    a, b = map(int, input().split())
    E[a-1].append(b-1)  # 双方向の情報
    E[b-1].append(a-1)
    
DP = [1] * N
CN = [0] * N

dfs(0)
bfs(0)

for i in DP:
    print(i)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Fri May  8 12:10:59 2020

@author: ybt07
"""

import sys
sys.setrecursionlimit(3*10**5)  # 繰り返し制限

# 組み合わせ
N = 2*10**5   # 問題サイズに合わせて変えておく
MOD = 10**9 + 7

# modint
# https://qiita.com/wotsushi/items/c936838df992b706084c

class ModInt:
    def __init__(self, x):
        self.x = x % MOD

    def __str__(self):
        return str(self.x)

    __repr__ = __str__

    def __add__(self, other):
        return (
            ModInt(self.x + other.x) if isinstance(other, ModInt) else
            ModInt(self.x + other)
        )

    def __sub__(self, other):
        return (
            ModInt(self.x - other.x) if isinstance(other, ModInt) else
            ModInt(self.x - other)
        )

    def __mul__(self, other):
        return (
            ModInt(self.x * other.x) if isinstance(other, ModInt) else
            ModInt(self.x * other)
        )

    # / : 商。　逆元はフェルマーの小定理を利用している
    '''
    def __truediv__(self, other):
        return (
            ModInt(
                self.x * pow(other.x, MOD - 2, MOD)
            ) if isinstance(other, ModInt) else
            ModInt(self.x * pow(other, MOD - 2, MOD))
        )
    '''
    def __truediv__(self, other):
        return (
            ModInt(
                self.x * inv[other.x]
            ) if isinstance(other, ModInt) else
            ModInt(self.x * inv[other])
        )


    # ** : 指数
    def __pow__(self, other):
        return (
            ModInt(pow(self.x, other.x, MOD)) if isinstance(other, ModInt) else
            ModInt(pow(self.x, other, MOD))
        )

    # x が Modint、y が通常の int の場合に、y.__add__(x) に対して、何を適用するか、定義している（→ x.__add__(y)を呼べ） 
    __radd__ = __add__

    def __rsub__(self, other):
        return (
            ModInt(other.x - self.x) if isinstance(other, ModInt) else
            ModInt(other - self.x)
        )

    __rmul__ = __mul__

    def __rtruediv__(self, other):
        return (
            ModInt(
                other.x * pow(self.x, MOD - 2, MOD)
            ) if isinstance(other, ModInt) else
            ModInt(other * pow(self.x, MOD - 2, MOD))
        )

    def __rpow__(self, other):
        return (
            ModInt(pow(other.x, self.x, MOD)) if isinstance(other, ModInt) else
            ModInt(pow(other, self.x, MOD))
        )

def cmb(n, r):
    if ( r<0 or r>n ):
        return 0
    r = min(r, n-r)
    return ModInt(fac[n] * facinv[r] * facinv[n-r])

fac = [1, 1] # 元テーブル
facinv = [1, 1] #逆元テーブル
inv = [0, 1] #逆元テーブル計算用テーブル

for i in range(2, N):
    fac.append( ( fac[-1] * i ) % MOD )
    inv.append( ( -inv[MOD % i] * (MOD//i) ) % MOD )
    facinv.append( (facinv[-1] * inv[-1]) % MOD )

# 部分木のDP値を求めていく
# u : 求める頂点
# 親（親側に辿らないように） p

def dfs(u, p = -1):

    global DP, CN, E
    
    tmp_ans = 1
    tmp_cn = 0  # （自分を含む）部分木のノード数

    # u から出ている頂点 v
    for v in E[u]:
        if v != p:  # 親への辺以外について
            DP[v], CN[v] = dfs(v, u)
            tmp_cn += CN[v]
            tmp_ans *= DP[v] * cmb(tmp_cn, CN[v])
    DP[u] = tmp_ans
    CN[u] = tmp_cn + 1
            
    return tmp_ans, tmp_cn + 1

# 各頂点の真のDP値を求めていく

def bfs(u, p=-1):
    
    global DP, E
    
    tmp_ans = DP[u]
    tmp_cn = 1
    
    for v in E[u]:  # 各vに対して「真のDP値」を求めていく
        if v == p:
            continue
            
        # DP[u] と DP[v] から DP[v <- u] を求める
        tmp_cn = N - CN[v]  # v から見たときの u の部分木の要素数
        # (A) tmp_ans = DP[u] / DP[v] / cmb(N - 1, CN[v])  # DP[u](を除いた場合)
                
        # DP[u <- v] を使って、DP[v] を更新する
        # (B) DP[v] = DP[v] * tmp_ans * cmb(N-1, tmp_cn)

                
        # (A)(B) を整理して
        DP[v] = DP[u] * CN[v] / tmp_cn 

        bfs(v, u)
    
    return

# 入力処理
N = int(input())  # 頂点数
E = [[] for _ in range(N)]  # 辺の情報

for _ in range(N - 1):
    a, b = map(int, input().split())
    E[a-1].append(b-1)  # 双方向の情報
    E[b-1].append(a-1)
    
DP = [ModInt(1)] * N
CN = [0] * N

dfs(0)
bfs(0)

for i in DP:
    print(i)