Problem:
 Score : 100 points    Problem Statement There is a tree with N vertices, numbered 1, 2, \ldots, N .
For each i ( 1 \leq i \leq N - 1 ), the i -th edge connects Vertex x_i and y_i .  Taro has decided to paint each vertex in white or black, so that any black vertex can be reached from any other black vertex by passing through only black vertices.  You are given a positive integer M .
For each v ( 1 \leq v \leq N ), answer the following question:   Assuming that Vertex v has to be black, find the number of ways in which the vertices can be painted, modulo M .       Constraints  All values in input are integers.  1 \leq N \leq 10^5  2 \leq M \leq 10^9  1 \leq x_i, y_i \leq N  The given graph is a tree.         Input Input is given from Standard Input in the following format:  N  M  x_1  y_1  x_2  y_2  :  x_{N - 1}  y_{N - 1}       Output Print N lines.
The v -th ( 1 \leq v \leq N ) line should contain the answer to the following question:   Assuming that Vertex v has to be black, find the number of ways in which the vertices can be painted, modulo M .         Sample Input 1 3 100
1 2
2 3      Sample Output 1 3
4
3  There are seven ways to paint the vertices, as shown in the figure below.
Among them, there are three ways such that Vertex 1 is black, four ways such that Vertex 2 is black and three ways such that Vertex 3 is black.        Sample Input 2 4 100
1 2
1 3
1 4      Sample Output 2 8
5
5
5       Sample Input 3 1 100      Sample Output 3 1       Sample Input 4 10 2
8 5
10 8
6 5
1 5
4 8
2 10
3 6
9 2
1 7      Sample Output 4 0
0
1
1
1
0
1
0
1
1  Be sure to print the answers modulo M .

Solution (Python):
import sys
sys.setrecursionlimit(4100000)

def os(): return input()
def oi(): return int(input())
def oli(): return map(int, input().split())
def olai(): return list(map(int, input().split()))
def olas(): return list(input().split())
def mlai(L): return [int(input()) for _ in range(L)]
def mlas(L): return [input() for _ in range(L)]
def ar(a, b, c=-1, d=-1, INIT=0):
    if(c==-1): return [[INIT]*b for _ in range(a)]
    if(d==-1): return [[[INIT]*c for _ in range(b)] for __ in range(a)]
    return [[[[INIT]*d for _ in range(c)] for __ in range(b)] for ___ in range(a)]

n, m = oli()







zero = 1


def step(x):
    return x+1

def merge(x, y):
    return (x*y)%m

G = [[] for _ in range(100001)]
down_data = [zero for _ in range(100001)]
dat = [zero for _ in range(100001)]

def dfs(now, parent):
    cnt = 0
    for to in G[now]:
        if(to==parent): continue
        cnt += 1
        dfs(to, now)
        down_data[now] = merge(down_data[now], step(down_data[to]))

def dfs_rev(now, parent, rev):
    
    left = []
    right = []
    cnt = 0
    for to in G[now]:
        if(to==parent): continue
        if(len(left)==0): left.append(step(down_data[to]))
        else: left.append(merge(left[cnt-1], step(down_data[to])))
        cnt += 1
    cnt = 0
    for to in reversed(G[now]):
        if(to==parent): continue
        if(len(right)==0): right.append(step(down_data[to]))
        else: right.append(merge(right[cnt-1], step(down_data[to])))
        cnt += 1
    cnt = 0
    dat[now] = merge(rev, down_data[now])

    for to in G[now]:
        if(to==parent): continue
        x = zero if cnt==0 else left[cnt-1]
        y = zero if cnt==len(right)-1 else right[len(right)-2-cnt]
        dfs_rev(to, now, step(merge(rev, merge(x, y))))
        cnt += 1

def calc(N):
    root = -1
    for i in range(1, N+1):
        if(len(G[i]) == 1 or len(G[i]) == 0):
            root = i
            break
    dfs(root, -1)
    dfs_rev(root, -1, zero)


for i in range(n-1):
    a, b = oli()
    G[a].append(b)
    G[b].append(a)
calc(n)
for i in range(1, n+1):
    print(dat[i])

Solution (Python):
def main():
    import sys
    input = sys.stdin.readline

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

    """ここから変更"""
    
    def op(a, b):
        return (a * (b + 1))%mod

    
    def cum_merge(a, b):
        return (a * b)%mod
    """ここまで変更"""

    
    
    
    def Rerooting(adj):
        N = len(adj) - 1
        st = [1]
        seen = [0] * (N + 1)
        seen[1] = 1
        par = [0] * (N + 1)
        child = [[] for _ in range(N + 1)]
        seq = []
        while st:
            v = st.pop()
            seq.append(v)
            for u in adj[v]:
                if not seen[u]:
                    seen[u] = 1
                    par[u] = v
                    child[v].append(u)
                    st.append(u)
        seq.reverse()
        dp = [1] * (N + 1)
        left = [1] * (N + 1)
        right = [1] * (N + 1)
        for v in seq:
            tmp = 1
            for u in child[v]:
                left[u] = tmp
                tmp = op(tmp, dp[u])
            tmp = 1
            for u in reversed(child[v]):
                right[u] = tmp
                tmp = op(tmp, dp[u])
            dp[v] = tmp

        seq.reverse()
        from_par = [0] * (N + 1)
        for v in seq:
            if v == 1:
                continue
            from_par[v] = op(cum_merge(left[v], right[v]), from_par[par[v]])
            dp[v] = op(dp[v], from_par[v])

        return dp

    dp = Rerooting(adj)
    for i in range(1, N+1):
        print(dp[i])


if __name__ == '__main__':
    main()

Solution (Python):
def examA():
    N = I()
    H = LI()
    dp = [inf]*(N)
    dp[0] = 0
    for i in range(N-1):
        dp[i+1] = min(dp[i+1],dp[i]+abs(H[i+1]-H[i]))
        if i<N-2:
            dp[i + 2] = min(dp[i + 2], dp[i]+abs(H[i + 2] - H[i]))
    ans = dp[-1]
    print(ans)
    return

def examB():
    N, K = LI()
    H = LI()
    dp = [inf]*N
    dp[0] = 0
    for i in range(N):
        for k in range(1,K+1):
            if i+k>=N:
                break
            if dp[i+k]>dp[i]+abs(H[i+k]-H[i]):
                dp[i+k] = dp[i]+abs(H[i+k]-H[i])
    ans = dp[-1]
    print(ans)
    return

def examC():
    N = I()
    A = [0]*N; B = [0]*N; C = [0]*N
    for i in range(N):
        A[i],B[i],C[i] = LI()
    dp = [[0]*3 for _ in range(N+1)]
    for i in range(N):
        dp[i+1][0] = max(dp[i][1],dp[i][2]) + A[i]
        dp[i + 1][1] = max(dp[i][0], dp[i][2]) + B[i]
        dp[i + 1][2] = max(dp[i][1], dp[i][0]) + C[i]
    ans = max(dp[N])
    print(ans)
    return

def examD():
    ans = 0
    print(ans)
    return

def examE():
    ans = 0
    print(ans)
    return

def examF():
    
    S = SI(); N = len(S)
    T = SI(); M = len(T)
    dp = [[0] * (M + 1) for _ in range(N + 1)]
    for i in range(N):
        for j in range(M):
            if S[i] == T[j]:
                dp[i + 1][j + 1] = max(dp[i + 1][j + 1], dp[i][j] + 1)
            dp[i+1][j+1] = max(dp[i+1][j+1], dp[i+1][j], dp[i][j+1])

    i = N; j = M
    ans = []
    while i > 0 and j > 0:
        if dp[i][j] == dp[i-1][j]:
            i -= 1
        elif dp[i][j] == dp[i][j-1]:
            j -= 1
        else:
            ans.append(S[i-1])
            i -= 1
            j -= 1
    print("".join(ans[::-1]))
    return

def examG():
    
    
    def topological_sort(n,outs,ins):
        q = deque(v1 for v1 in range(n) if ins[v1] == 0)
        res = []
        while q:
            v1 = q.popleft()
            res.append(v1)
            for v2 in outs[v1]:
                ins[v2] -= 1
                if ins[v2] == 0:
                    q.append(v2)
        return res
    N, M = LI()
    V = [[]for _ in range(N)]
    start = [0]*N
    for _ in range(M):
        x,y = LI()
        x -= 1; y -= 1
        V[x].append(y)
        start[y] += 1
    Order = topological_sort(N, V, start)

    dp = [0]*N
    for i in Order:
        for v in V[i]:
            dp[v] = max(dp[v],dp[i]+1)
    ans = max(dp)
    print(ans)
    return

def examH():
    H, W = LI()
    A = [SI() for _ in range(H)]
    dp = [[0]*W for _ in range(H)]
    dp[0][0] = 1
    for i in range(H):
        for j in range(W):
            if A[i][j]=="
                continue
            dp[i][j] %=mod
            if i+1<H and dp[i+1][j]!="
                dp[i+1][j] +=dp[i][j]
            if j+1<W and dp[i][j+1]!="
                dp[i][j+1] +=dp[i][j]
    ans = dp[-1][-1]
    print(ans)
    return

def examI():
    N = I()
    P = LFI()
    dp = [[0]*(N+1) for _ in range(N+1)]
    dp[0][0] = 1
    for i in range(N):
        for j in range(i+1):
            dp[i+1][j+1] += dp[i][j]*P[i]
            dp[i+1][j] += dp[i][j]*(1-P[i])
    ans = 0
    for v in dp[N][(1+N//2):]:
        ans += v
    print(ans)
    return

def examJ():
    N = I()
    A = LI()
    dp = [[[0]*(N+1) for _ in range(N+1)]for _ in range(N+1)]
    S = Counter(A)
    print(S)
    dp[S[1]][S[2]][S[3]] = 0
    que = deque()
    que.append((S[1],S[2],S[3]))
    used = defaultdict(set)
    while(que):
        n1,n2,n3 = que.popleft()
        if used[(n1,n2,n3)]:
            continue
        used[(n1,n2,n3)] = True
        now = n1+n2+n3
        if n1>0:
            dp[n1-1][n2][n3] += dp[n1][n2][n3] + N/now * n1/now
            que.append((n1-1, n2, n3))
        if n2>0:
            dp[n1+1][n2-1][n3] += dp[n1][n2][n3] + N/now * n2/now
            que.append((n1+1,n2-1,n3))
        if n3>0:
            dp[n1][n2+1][n3-1] += dp[n1][n2][n3] + N/now * n3/now
            que.append((n1,n2+1,n3-1))

    ans = dp[0][0][0]
    print(ans)
    return

def examK():
    N, K = LI()
    A = LI()
    dp = [-1]*(K+1)
    for i in range(1,K+1):
        flag = False
        for a in A:
            if a>i:
                break
            if dp[i-a]==-1:
                flag = True
                break
        if flag:
            dp[i] = 1

    ans = dp[K]
    if ans==1:
        print("First")
    else:
        print("Second")
    return

def examM():
    N, K = LI()
    A = LI()
    dp = [[0]*(K+1) for _ in range(N+1)]
    dp[0][0] = 1
    for i in range(N):
        cum = [0]*(K+1)
        cum[0] = dp[i][0]
        for c in range(K):
            cum[c+1] = cum[c] + dp[i][c+1]
        for j in range(K+1):
            if j<=A[i]:
                dp[i+1][j] = cum[j]
            else:
                dp[i+1][j] = cum[j] - cum[j-A[i]-1]
            dp[i+1][j] %=mod

    ans = dp[N][K]%mod
    print(ans)
    return

def examN():
    N = I()
    A = LI()
    cumA = [0]*(N+1)
    for i in range(N):
        cumA[i+1] = cumA[i]+A[i]
    dp = [[inf]*(N) for _ in range(N)]
    for i in range(N):
        dp[0][i] = 0
    for i in range(N-1):
        for j in range(N-i-1):
            for k in range(i+1):
                cur = dp[i-k][j+k+1]+dp[k][j]+cumA[i+j+2]-cumA[j]
                dp[i+1][j] = min(dp[i+1][j],cur)

    ans = dp[N-1][0]
    print(ans)
    return

def examO():
    N = I()
    A = [LI() for _ in range(N)]
    loop = 2**N
    dp = [[0]*loop for _ in range(N+1)]
    dp[0][0] = 1
    for mask in range(loop):
        cur = 0
        for j in range(N):
            if mask&(1<<j)==(1<<j):
                cur +=1
        for i in range(N):
            if mask&(1<<i)==0 and A[i][cur]==1:
                dp[cur+1][mask|(1<<i)] += dp[cur][mask]
                dp[cur + 1][mask | (1 << i)] %=mod

    ans = dp[N][loop-1]
    print(ans)
    return

def examP():
    def dfs_dp(n,s,fords,visited):
        W = 1; B = 1
        visited[s] = True
        for v in fords[s]:
            if visited[v]:
                continue
            cur = dfs_dp(n, v, fords,visited)
            W *= sum(cur)
            B *= cur[0]
            W %= mod
            B %= mod

        return (W,B)
    N = I()
    V = [[]for _ in range(N)]
    for _ in range(N-1):
        x,y = LI()
        x -=1; y -=1
        V[x].append(y)
        V[y].append(x)
    visited = [False]*N
    ans = dfs_dp(N,0,V,visited)
    print(sum(ans)%mod)
    return

def examQ():
    
    class segment_():
        def __init__(self, A, n, segfunc):
            
            self.ide_ele = 0
            
            self.num = 1 << (n - 1).bit_length()
            self.seg = [self.ide_ele] * 2 * self.num
            self.segfunc = segfunc
            
            for i in range(n):
                self.seg[i + self.num] = A[i]
                
            for i in range(self.num - 1, 0, -1):
                self.seg[i] = self.segfunc(self.seg[2 * i], self.seg[2 * i + 1])

        def update(self, k, r):
            k += self.num
            self.seg[k] = r
            while k:
                k >>= 1
                self.seg[k] = self.segfunc(self.seg[k * 2], self.seg[k * 2 + 1])

        
        def update1(self, k):
            k += self.num
            self.seg[k] += 1
            while k:
                k >>= 1
                self.seg[k] = self.segfunc(self.seg[k * 2], self.seg[k * 2 + 1])

        def updateneg1(self, k):
            k += self.num
            self.seg[k] -= 1
            while k:
                k >>= 1
                self.seg[k] = self.segfunc(self.seg[k * 2], self.seg[k * 2 + 1])

        def query(self, p, q):
            if q < p:
                return self.ide_ele
            p += self.num;
            q += self.num
            res = self.ide_ele
            while p < q:
                if p & 1 == 1:
                    res = self.segfunc(res, self.seg[p])
                    p += 1
                if q & 1 == 1:
                    q -= 1
                    res = self.segfunc(res, self.seg[q])
                p >>= 1;
                q >>= 1
            return res
    N = I()
    H = LI()
    maxH = max(H)
    A = LI()
    Seg_max = segment_([0]*(maxH+1), (N+1), lambda a, b: max(a,b))
    dp = [0]*(maxH+1)
    cur = 0
    for i in range(N):
        h = H[i]
        cur = Seg_max.query(0,h+1)
        dp[i] = cur + A[i]
        Seg_max.update(h,dp[i])
    ans = max(dp)
    print(ans)
    return

def examR():
    def list_dot(A1,A2):
        res = [[0]*len(A2) for _ in range(len(A1))]
        for i in range(len(A1)):
            for j in range(len(A2)):
                cur = 0
                for k in range(len(A1[0])):
                    cur += A1[i][k]*A2[k][j]
                res[i][j] = cur%mod
        return res
    N, K = LI()
    A = [LI() for _ in range(N)]
    now = [[1]*N]
    while(K>0):
        if K%2==1:
            now = list_dot(now,A)
        K //=2
        A = list_dot(A,A)
    ans = 0
    for i in now:
        for k in i:
            ans += k
            ans %= mod
    print(ans)
    return

def examS():
    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))
            )
    def ketadp(a,D):
        n = len(a)
        dp = [[[ModInt(0)]*D for _ in range(2)] for _ in range(n+1)]
        dp[0][0][0] = 1
        for i, less, hasD in itertools.product(range(n), (0, 1), range(D)):
            max_d = 9 if less else int(a[i])
            for d in range(max_d + 1):
                less_ = less or d < max_d
                hasD_ = (hasD + d)%D
                dp[i + 1][less_][hasD_] += dp[i][less][hasD]

        ans = sum(dp[n][less][0] for less in (0, 1))
        return ans
    K = SI()
    D = I()
    ans = ketadp(K,D)
    ans = ans-1
    print(ans)
    return

def examT():
    return

def examU():
    N = I()
    A = [LI() for _ in range(N)]
    mask = 2**N
    cst = [0]*mask
    for i in range(mask):
        cur = 0
        for j in range(N):
            for k in range(j+1,N):
                if i&(1<<j)==(1<<j) and i&(1<<k)==(1<<k):
                    cur += A[j][k]
        cst[i] = cur
    dp = [0]*mask
    for m in range(mask):
        maskT = m
        while(maskT > 0):
            cur = dp[m-maskT] + cst[maskT]
            dp[m] = max(dp[m], cur)

            
            maskT = (maskT - 1) & m

    ans = dp[-1]
    print(ans)
    return



def examV():
    N, M = LI()
    V = [set() for _ in range(N)]
    for _ in range(N-1):
        a, b = LI()
        a -= 1; b -= 1
        V[a].add(b)
        V[b].add(a)
    B = [0]*N
    ans = [0]*N

    if N == 1:
        print(1)
        return

    def dfs1(s,p):
        B[s] = 1
        for ne in V[s]:
            if ne==p:
                continue
            B[s] *= (dfs1(ne,s)+1)
            B[s] %= M
        return B[s]

    def dfs2(s,p):
        rep = 1
        for to in V[s]:
            rep *= (B[to] +1)
            rep %= M
        ans[s] = rep

        n = len(V[s])
        L = [0]*n; R = [0]*n
        for i,ne in enumerate(V[s]):
            L[i] = R[i] = B[ne]+1
        for i in range(1,n):
            L[i] *= L[i-1]
            L[i] %= M
        for i in range(1,n-1)[::-1]:
            R[i] *= R[i+1]
            R[i] %= M
        for i,ne in enumerate(V[s]):
            if ne!=p:
                B[s] = 1
                if i:
                    B[s] *= L[i-1]
                    B[s] %= M
                if i+1<n:
                    B[s] *= R[i+1]
                B[s] %= M
                dfs2(ne,s)

        return

    ans[0] = dfs1(0,-1)
    
    dfs2(0,-1)
    for v in ans:
        print(v%M)
    return

def examX():
    N = I()
    W = [[] for _ in range(N)]
    for i in range(N):
        W[i] = LI()
    W.sort(key=lambda x:x[1])
    maxS = W[-1][1]
    print(W)
    dp = [[0]*(maxS+2) for _ in range(N+1)]
    for i in range(N):
        ns = W[i][1]
        nw = W[i][0]
        nv = W[i][2]
        for j in range(maxS+2):
            dp[i+1][j] = max(dp[i+1][j],dp[i][j])
        for j in range(ns+1):
            dp[i+1][min(j+nw,maxS+1)] = max(dp[i+1][j],dp[i][j]+nv)
    ans = max(dp[N])
    print(dp)
    print(ans)
    return

import sys,copy,bisect,itertools,heapq,math
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
def LFI(): return list(map(float,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,mod2,inf,alphabet,MOD
mod = 10**9 + 7
mod2 = 998244353
MOD = mod
inf = 10**18
alphabet = [chr(ord('a') + i) for i in range(26)]

sys.setrecursionlimit(10**6)

if __name__ == '__main__':
    examV()

"""

"""

Solution (Python):


import sys
input = lambda : sys.stdin.readline().strip()

n,m = map(int, input().split())
mod = m
G = [[] for i in range(n)]
for i in range(n-1):
    a,b = map(int, input().split())
    a,b = a-1,b-1
    G[a].append(b)
    G[b].append(a)

from collections import deque
def dfs(root):
    que = deque()
    que.append((root, -1))
    order = []
    while que:
        cur,prev = que.popleft()
        order.append(cur)
        for to in G[cur]:
            if to != prev:
                que.append((to, cur))
    return order

order = dfs(0)

child = set()
down = [1]*n
for cur in reversed(order):
    tmp = 1
    for to in G[cur]:
        if to in child:
            tmp *= (down[to]+1)
            tmp %= mod
    down[cur] = tmp
    child.add(cur)

ans = [0]*n
que = deque()
que.append((0, -1, 1))
while que:
    cur, prev, parent = que.popleft()

    left = [1]
    for to in G[cur]:
        tmp = down[to]
        if to == prev:
            tmp = parent
        left.append(left[-1]*(tmp+1)%mod)

    right = [1]
    for to in reversed(G[cur]):
        tmp = down[to]
        if to == prev:
            tmp = parent
        right.append(right[-1]*(tmp+1)%mod)
    ans[cur] = left[-1]

    m = len(G[cur])
    for i, to in enumerate(G[cur]):
        if to != prev:
            que.append((to, cur, left[i]*right[m-i-1]))

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

Solution (Python):
import sys
input = sys.stdin.readline
from collections import deque
N, M = map(int, input().split())
X = [[] for i in range(N)]
for i in range(N-1):
    x, y = map(int, input().split())
    X[x-1].append(y-1)
    X[y-1].append(x-1)

P = [-1] * N
Q = deque([0])
R = []
while Q:
    i = deque.popleft(Q)
    R.append(i)
    for a in X[i]:
        if a != P[i]:
            P[a] = i
            X[a].remove(i)
            deque.append(Q, a)

BU = [0] * N
TD = [1] * N
for i in R[::-1]:
    a = 1
    for j in X[i]:
        a = a * (BU[j] + 1) % M
    BU[i] = a
for i in R:
    c = len(X[i])
    AL = [1] * (c + 1)
    AR = [1] * (c + 1)
    for j in range(c):
        AL[j+1] = AL[j] * (BU[X[i][j]] + 1) % M
    for j in range(c)[::-1]:
        AR[j] = AR[j+1] * (BU[X[i][j]] + 1) % M
    for j in range(c):
        TD[X[i][j]] = (TD[i] * AL[j] * AR[j+1] + 1) % M

for i in range(N):
    print(BU[i] * TD[i] % M)

Solution (Python):
import sys
input = sys.stdin.readline

from collections import deque
from functools import reduce
f = lambda a: (a+1) % M
g = lambda a, b: a * b % M
init = 1

N, M = map(int, input().split())
X = [[] for i in range(N)]
for i in range(N-1):
    x, y = map(int, input().split())
    X[x-1].append(y-1)
    X[y-1].append(x-1)

P = [-1] * N
Q = deque([0])
T = []
while Q:
    i = deque.popleft(Q)
    T.append(i)
    for a in X[i]:
        if a != P[i]:
            P[a] = i
            X[a].remove(i)
            deque.append(Q, a)

BU = [0] * N 
TD = [1] * N 
for i in T[::-1]:
    BU[i] = reduce(g, [f(BU[j]) for j in X[i]]) if len(X[i]) else init

for i in T:
    B = [1] * (len(X[i]) + 1)
    for k, j in enumerate(X[i]):
        B[k+1] = g(B[k], f(BU[j]))
    a = init
    for k in range(len(X[i]))[::-1]:
        j = X[i][k]
        TD[j] = f(g(TD[i], g(a, B[k])))
        a = g(a, f(BU[j]))

for t in [g(a, b) for a, b in zip(BU, TD)]:
    print(t)

Solution (Python):
from collections import deque
from functools import reduce
f = lambda a: (a+1) % M
g = lambda a, b: a * b % M
init = 1

N, M = map(int, input().split())
X = [[] for i in range(N)]
for i in range(N-1):
    x, y = map(int, input().split())
    X[x-1].append(y-1)
    X[y-1].append(x-1)

P = [-1] * N
Q = deque([0])
T = []
while Q:
    i = deque.popleft(Q)
    T.append(i)
    for a in X[i]:
        if a != P[i]:
            P[a] = i
            X[a].remove(i)
            deque.append(Q, a)

BU = [0] * N 
TD = [1] * N 
for i in T[::-1]:
    BU[i] = reduce(g, [f(BU[j]) for j in X[i]]) if len(X[i]) else init

for i in T:
    B = [1] * (len(X[i]) + 1)
    for k, j in enumerate(X[i]):
        B[k+1] = g(B[k], f(BU[j]))
    a = init
    for k in range(len(X[i]))[::-1]:
        j = X[i][k]
        TD[j] = f(g(TD[i], g(a, B[k])))
        a = g(a, f(BU[j]))

for t in [g(a, b) for a, b in zip(BU, TD)]:
    print(t)

Solution (Python):
from collections import deque
from functools import reduce
def f(a):
    return (a + 1) % M
def g(a, b):
    return a * b % M
init = 1

N, M = map(int, input().split())
X = [[] for i in range(N)]
for i in range(N-1):
    x, y = map(int, input().split())
    X[x-1].append(y-1)
    X[y-1].append(x-1)

P = [-1] * N
Q = deque([0])
T = []
while Q:
    i = deque.popleft(Q)
    T.append(i)
    for a in X[i]:
        if a != P[i]:
            P[a] = i
            X[a].remove(i)
            deque.append(Q, a)

BU = [0] * N 
TD = [1] * N 
for i in T[::-1]:
    BU[i] = reduce(g, [f(BU[j]) for j in X[i]]) if len(X[i]) else init

for i in T:
    B = [1] * (len(X[i]) + 1)
    for k, j in enumerate(X[i]):
        B[k+1] = g(B[k], f(BU[j]))
    a = init
    for k in range(len(X[i]))[::-1]:
        j = X[i][k]
        TD[j] = f(g(TD[i], g(a, B[k])))
        a = g(a, f(BU[j]))

for t in [g(a, b) for a, b in zip(BU, TD)]:
    print(t)

Solution (Python):
import sys
input = sys.stdin.readline
from collections import deque
N, M = map(int, input().split())
X = [[] for i in range(N)]
for i in range(N-1):
    x, y = map(int, input().split())
    X[x-1].append(y-1)
    X[y-1].append(x-1)

P = [-1] * N
Q = deque([0])
R = []
while Q:
    i = deque.popleft(Q)
    R.append(i)
    for a in X[i]:
        if a != P[i]:
            P[a] = i
            X[a].remove(i)
            deque.append(Q, a)

A = [0] * N
AA = [1] * N
for i in R[::-1]:
    a = 1
    for j in X[i]:
        a = a * (A[j] + 1) % M
    A[i] = a
for i in R:
    B = [1] * (len(X[i]) + 1)
    for j in range(len(X[i])):
        B[j+1] = B[j] * (A[X[i][j]] + 1) % M
    a = 1
    for j in range(len(X[i]))[::-1]:
        t = a * B[j]
        a = a * (A[X[i][j]] + 1) % M
        AA[X[i][j]] = (AA[i] * t + 1) % M

for t in [a * aa % M for a, aa in zip(A, AA)]:
    print(t)

Solution (Python):
def main():
    import sys
    input = sys.stdin.readline

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

    st = [1]
    seen = [0] * (N+1)
    seen[1] = 1
    par = [0] * (N+1)
    child = [[] for _ in range(N+1)]
    seq = []
    while st:
        v = st.pop()
        seq.append(v)
        for u in adj[v]:
            if not seen[u]:
                seen[u] = 1
                par[u] = v
                child[v].append(u)
                st.append(u)
    seq.reverse()
    dp = [1] * (N+1)
    left = [1] * (N+1)
    right = [1] * (N+1)
    for v in seq:
        tmp = 1
        for u in child[v]:
            left[u] = tmp
            tmp = (tmp * (dp[u] + 1)) % mod
        tmp = 1
        for u in reversed(child[v]):
            right[u] = tmp
            tmp = (tmp * (dp[u] + 1)) % mod
        dp[v] = tmp

    seq.reverse()
    dp2 = [0] * (N+1)
    for v in seq:
        if v == 1:
            continue
        dp2[v] = ((left[v] * right[v])%mod * (dp2[par[v]]+1))%mod
        dp[v] = (dp[v] * (dp2[v]+1))%mod

    for i in range(1, N+1):
        print(dp[i])


if __name__ == '__main__':
    main()

Solution (Python):
from collections import deque
N, M = map(int, input().split())
d = [list() for _ in range(N+1)]
for _ in range(N-1):
    a, b = map(int, input().split())
    d[a].append(b)
    d[b].append(a)

queue=deque([1])
vs = set([1])
vs_bfs = list()
parents = [0] * (N+1)
while queue:
    v = queue.popleft()
    vs_bfs.append(v)
    for u in d[v]:
        if u in vs:
            continue
        parents[u] = v
        vs.add(u)
        queue.append(u)

dp = [0 for _ in range(N+1)]
dpl = [1 for _ in range(N+1)]
dpr = [1 for _ in range(N+1)]
for v in vs_bfs[::-1]:
    t = 1
    for u in d[v]:
        if u == parents[v]:
            continue
        dpl[u] = t
        t = (t * (dp[u]+1)) % M
    t = 1
    for u in d[v][::-1]:
        if u == parents[v]:
            continue
        dpr[u] = t
        t = (t * (dp[u]+1)) % M
    dp[v] = t

dp2 = [0]*(N+1)
for v in vs_bfs:
    if v == 1:
        dp2[v] = 1
        continue
    p = parents[v]
    dp2[v] = (dp2[p] * (dpl[v]*dpr[v]) +1)% M


r = [0]*N
for i in range(1, N+1):
    r[i-1] = str(dp[i] * dp2[i] % M)
print("\n".join(r))

Solution (Python):

import sys
from collections import defaultdict
sys.setrecursionlimit(10**8)


class Graph(object):
    def __init__(self, N):
        self.N = N
        self.E = defaultdict(list)

    def add_edge(self, f, t, w=1):
        self.E[f].append((t, w))


def solve(N: int, M: int, x: "List[int]", y: "List[int]"):
    g = Graph(N)
    for xx, yy in zip(x, y):
        g.add_edge(xx-1, yy-1)
        g.add_edge(yy-1, xx-1)

    dp = [0]*N

    def dfs(node, par=-1):
        dp[node] = 1
        for child, _ in g.E[node]:
            if child == par:
                continue
            dp[node] *= dfs(child, node) + 1
            dp[node] %= M
        return dp[node]

    ans = [0]*N

    def dfs_2(node, par=-1):
        ans[node] = 1
        for child, _ in g.E[node]:
            ans[node] *= dp[child]+1
            ans[node] %= M

        
        K = len(g.E[node])
        left, right = [1]*K, [1]*K
        for i in range(K):
            t, w = g.E[node][i]
            left[i] = left[i-1]*(dp[t]+1)
            left[i] %= M
        for i in range(K-1, -1, -1):
            t, w = g.E[node][i]
            if i != K-1:
                right[i] = right[i+1]*(dp[t]+1)
            else:
                right[i] = dp[t]+1
            right[i] %= M

        for i in range(K):
            child, _ = g.E[node][i]
            if child == par:
                continue
            dp[node] = 1
            if i:
                dp[node] *= left[i-1]
            if i+1 < K:
                dp[node] *= right[i+1]
            dp[node] %= M
            dfs_2(child, node)
    dfs(0)
    dfs_2(0)

    for a in ans:
        print(a % M)

    return


def main():

    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  
    M = int(next(tokens))  
    x = [int()] * (N - 1)  
    y = [int()] * (N - 1)  
    for i in range(N - 1):
        x[i] = int(next(tokens))
        y[i] = int(next(tokens))
    solve(N, M, x, y)


if __name__ == '__main__':
    main()