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.



Sample input:
3 100
1 2
2 3


Sample output:
3
4
3

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3

from collections import defaultdict
#from heapq import heappush, heappop
#import numpy as np
import sys

sys.setrecursionlimit(10**6)
input = sys.stdin.buffer.readline
INF = 10 ** 9 + 1  # sys.maxsize # float("inf")
MOD = 10 ** 9 + 7

debug_indent = 0


def debug(*x):
    global debug_indent
    x = list(x)
    indent = 0
    if x[0].startswith("enter") or x[0][0] == ">":
        indent = 1
    if x[0].startswith("leave") or x[0][0] == "<":
        debug_indent -= 1
    x[0] = "  " * debug_indent + x[0]
    print(*x, file=sys.stderr)
    debug_indent += indent


def solve(N, M, edges):

    cache = {}

    for v in edges:
        if len(edges[v]) == 1:
            cache[(v, edges[v][0])] = (1, 0)

    def visit(parent, self):
        "return (blackroot, whiteroot)"
        cacheindex = (self, parent)
        if cacheindex in cache:
            return cache[cacheindex]

        total = 1
        fw_b = 1  # full white or black
        one_black = 0  # only one black-root

        if parent != 0 and self in precompute:
            totals, fw_bs, one_blacks = precompute[self]
            total = totals[parent]
            fw_b = fw_bs[parent]
            one_black = one_blacks[parent]
        else:
            for child in edges[self]:
                if child == parent:
                    continue
                b, w = visit(self, child)
                total *= (1 + w + b)
                total %= M
                fw_b *= (1 + b)
                fw_b %= M
                one_black += b

        ret_b = ret_w = 0
        # when all child are fill-white, one black-root and one full-white
        ret_b += 1
        # when only one child is black-root and others are full-white
        # both white-root and black-root are OK
        ret_b += one_black
        ret_w += one_black
        # when multiple black-root and no white-root, it should be black
        ret_b += (fw_b - one_black - 1)
        # otherwise there are one or more white-root, it should be white
        ret_w += total - fw_b

        ret_b %= M
        ret_w %= M

        if parent != 0:
            ret = (ret_b, ret_w)
            cache[cacheindex] = ret
            return ret
        else:
            return ret_b

    # precomputed product
    precompute = {}

    def calc_one_out_product(xs):
        n = len(xs)
        head = [0] * (n + 1)
        cur = 1
        for i in range(n):
            cur *= xs[i]
            head[i] = cur
        head[-1] = 1

        tail = [0] * (n + 1)
        cur = 1
        for i in range(n - 1, -1, -1):
            cur *= xs[i]
            tail[i] = cur
        tail[-1] = 1

        one_out_product = [head[i - 1] * tail[i + 1] for i in range(n)]
        return one_out_product

    for v in edges:
        n = len(edges[v])
        if n > 1:
            tmp_ret = [visit(v2, v) for v2 in edges[v]]
            _totals = calc_one_out_product([1 + b + w for b, w in tmp_ret])
            _fw_bs = calc_one_out_product([1 + b for b, w in tmp_ret])
            s = sum([b for b, w in tmp_ret])

            # change domain from i to v
            totals = [0] * (N + 1)
            fw_bs = [0] * (N + 1)
            one_blacks = [s] * (N + 1)
            for i, v2 in enumerate(edges[v]):
                totals[v2] = _totals[i]
                fw_bs[v2] = _fw_bs[i]
                one_blacks[v2] -= tmp_ret[i][0]
            precompute[v] = (totals, fw_bs, one_blacks)

    ret = [visit(0, i + 1) % M for i in range(N)]
    return ret


def main():
    # parse input
    N, M = map(int, input().split())
    edges = defaultdict(list)
    for i in range(N - 1):
        x, y = map(int, input().split())
        edges[x].append(y)
        edges[y].append(x)

    #print(*solve(N, M, edges), sep="\n")
    for x in solve(N, M, edges):
        print(x)


# tests
T1 = """
3 100
1 2
2 3
"""


def test_T1():
    """
    >>> as_input(T1)
    >>> main()
    3
    4
    3
    """


T2 = """
4 100
1 2
1 3
1 4
"""


def test_T2():
    """
    >>> as_input(T2)
    >>> main()
    8
    5
    5
    5
    """


T3 = """
1 100
"""


def test_T3():
    """
    >>> as_input(T3)
    >>> main()
    1
    """


T4 = """
10 2
8 5
10 8
6 5
1 5
4 8
2 10
3 6
9 2
1 7
"""


def test_T4():
    """
    >>> as_input(T4)
    >>> main()
    0
    0
    1
    1
    1
    0
    1
    0
    1
    1
    """


# def test_T5():
#     """
#     >>> edges = defaultdict(list)
#     >>> for i in range(100000 - 1):
#     ...     edges[i + 1].append(i + 2)
#     ...     edges[i + 2].append(i + 1)
#     >>> solve(100000, 5, edges)
#     """
# add tests above


def _test():
    import doctest
    doctest.testmod()


def as_input(s):
    "use in test, use given string as input file"
    import io
    global read, input
    f = io.StringIO(s.strip())

    def input():
        return bytes(f.readline(), "ascii")

    def read():
        return bytes(f.read(), "ascii")


USE_NUMBA = False
if (USE_NUMBA and sys.argv[-1] == 'ONLINE_JUDGE') or sys.argv[-1] == '-c':
    print("compiling")
    from numba.pycc import CC
    cc = CC('my_module')
    cc.export('solve', solve.__doc__.strip().split()[0])(solve)
    cc.compile()
    exit()
else:
    input = sys.stdin.buffer.readline
    read = sys.stdin.buffer.read

    if (USE_NUMBA and sys.argv[-1] != '-p') or sys.argv[-1] == "--numba":
        # -p: pure python mode
        # if not -p, import compiled module
        from my_module import solve  # pylint: disable=all
    elif sys.argv[-1] == "-t":
        print("testing")
        _test()
        sys.exit()
    elif sys.argv[-1] != '-p' and len(sys.argv) == 2:
        # input given as file
        input_as_file = open(sys.argv[1])
        input = input_as_file.buffer.readline
        read = input_as_file.buffer.read

    main()

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3

from collections import defaultdict
#from heapq import heappush, heappop
#import numpy as np
import sys

sys.setrecursionlimit(10**6)
input = sys.stdin.buffer.readline
INF = 10 ** 9 + 1  # sys.maxsize # float("inf")
MOD = 10 ** 9 + 7

debug_indent = 0


def debug(*x):
    global debug_indent
    x = list(x)
    indent = 0
    if x[0].startswith("enter") or x[0][0] == ">":
        indent = 1
    if x[0].startswith("leave") or x[0][0] == "<":
        debug_indent -= 1
    x[0] = "  " * debug_indent + x[0]
    print(*x, file=sys.stderr)
    debug_indent += indent


def solve(N, M, edges):
    cache = {}
    for v in edges:
        if len(edges[v]) == 1:
            cache[(v, edges[v][0])] = (1, 0)

    def visit(parent, self):
        "return (blackroot, whiteroot)"
        cacheindex = (self, parent)
        if cacheindex in cache:
            return cache[cacheindex]

        total = 1
        fw_b = 1  # full white or black
        one_black = 0  # only one black-root

        for child in edges[self]:
            if child == parent:
                continue
            b, w = visit(self, child)
            total *= (1 + w + b)
            total %= M
            fw_b *= (1 + b)
            fw_b %= M
            one_black += b

        ret_b = ret_w = 0
        # when all child are fill-white, one black-root and one full-white
        ret_b += 1
        # when only one child is black-root and others are full-white
        # both white-root and black-root are OK
        ret_b += one_black
        ret_w += one_black
        # when multiple black-root and no white-root, it should be black
        ret_b += (fw_b - one_black - 1)
        # otherwise there are one or more white-root, it should be white
        ret_w += total - fw_b

        ret_b %= M
        ret_w %= M

        if parent != 0:
            ret = (ret_b, ret_w)
            cache[cacheindex] = ret
            return ret
        else:
            return ret_b

    ret = [visit(0, i + 1) % M for i in range(N)]
    return ret


def main():
    # parse input
    N, M = map(int, input().split())
    edges = defaultdict(list)
    for i in range(N - 1):
        x, y = map(int, input().split())
        edges[x].append(y)
        edges[y].append(x)

    #print(*solve(N, M, edges), sep="\n")
    for x in solve(N, M, edges):
        print(x)


# tests
T1 = """
3 100
1 2
2 3
"""


def test_T1():
    """
    >>> as_input(T1)
    >>> main()
    3
    4
    3
    """


T2 = """
4 100
1 2
1 3
1 4
"""


def test_T2():
    """
    >>> as_input(T2)
    >>> main()
    8
    5
    5
    5
    """


T3 = """
1 100
"""


def test_T3():
    """
    >>> as_input(T3)
    >>> main()
    1
    """


T4 = """
10 2
8 5
10 8
6 5
1 5
4 8
2 10
3 6
9 2
1 7
"""


def test_T4():
    """
    >>> as_input(T4)
    >>> main()
    0
    0
    1
    1
    1
    0
    1
    0
    1
    1
    """


# def test_T5():
#     """
#     >>> edges = defaultdict(list)
#     >>> for i in range(100000 - 1):
#     ...     edges[i + 1].append(i + 2)
#     ...     edges[i + 2].append(i + 1)
#     >>> solve(100000, 5, edges)
#     """
# add tests above


def _test():
    import doctest
    doctest.testmod()


def as_input(s):
    "use in test, use given string as input file"
    import io
    global read, input
    f = io.StringIO(s.strip())

    def input():
        return bytes(f.readline(), "ascii")

    def read():
        return bytes(f.read(), "ascii")


USE_NUMBA = False
if (USE_NUMBA and sys.argv[-1] == 'ONLINE_JUDGE') or sys.argv[-1] == '-c':
    print("compiling")
    from numba.pycc import CC
    cc = CC('my_module')
    cc.export('solve', solve.__doc__.strip().split()[0])(solve)
    cc.compile()
    exit()
else:
    input = sys.stdin.buffer.readline
    read = sys.stdin.buffer.read

    if (USE_NUMBA and sys.argv[-1] != '-p') or sys.argv[-1] == "--numba":
        # -p: pure python mode
        # if not -p, import compiled module
        from my_module import solve  # pylint: disable=all
    elif sys.argv[-1] == "-t":
        print("testing")
        _test()
        sys.exit()
    elif sys.argv[-1] != '-p' and len(sys.argv) == 2:
        # input given as file
        input_as_file = open(sys.argv[1])
        input = input_as_file.buffer.readline
        read = input_as_file.buffer.read

    main()

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3

from collections import defaultdict
#from heapq import heappush, heappop
#import numpy as np
import sys

sys.setrecursionlimit(10**6)
input = sys.stdin.buffer.readline
INF = 10 ** 9 + 1  # sys.maxsize # float("inf")
MOD = 10 ** 9 + 7

debug_indent = 0


def debug(*x):
    global debug_indent
    x = list(x)
    indent = 0
    if x[0].startswith("enter") or x[0][0] == ">":
        indent = 1
    if x[0].startswith("leave") or x[0][0] == "<":
        debug_indent -= 1
    x[0] = "  " * debug_indent + x[0]
    print(*x, file=sys.stderr)
    debug_indent += indent


def solve(N, M, edges):
    pass

    ret_white = 0
    ret_total = 0

    from functools import lru_cache
    @lru_cache(maxsize=None)
    def visit(parent, self):
        "return (white, black)"
        if parent != 0 and len(edges[self]) == 1:
            return (1, 1)

        total = 1
        one_black = 0
        for child in edges[self]:
            if child == parent:
                continue
            w, b = visit(self, child)
            total *= (w + b)
            one_black *= b

        if parent != 0:
            ret = (
                1,
                (1 + one_black * 2 + (total - one_black - 1)) % M
            )
            return ret
        else:
            return total
    return [visit(0, i + 1) % M for i in range(N)]


def main():
    # parse input
    N, M = map(int, input().split())
    edges = defaultdict(list)
    for i in range(N - 1):
        x, y = map(int, input().split())
        edges[x].append(y)
        edges[y].append(x)

    print(*solve(N, M, edges), sep="\n")


# tests
T1 = """
3 100
1 2
2 3
"""


def test_T1():
    """
    >>> as_input(T1)
    >>> main()
    3
    4
    3
    """


T2 = """
4 100
1 2
1 3
1 4
"""


def test_T2():
    """
    >>> as_input(T2)
    >>> main()
    8
    5
    5
    5
    """


T3 = """
1 100
"""


def test_T3():
    """
    >>> as_input(T3)
    >>> main()
    1
    """


T4 = """
10 2
8 5
10 8
6 5
1 5
4 8
2 10
3 6
9 2
1 7
"""


def test_T4():
    """
    >>> as_input(T4)
    >>> main()
    0
    0
    1
    1
    1
    0
    1
    0
    1
    1
    """
# add tests above


def _test():
    import doctest
    doctest.testmod()


def as_input(s):
    "use in test, use given string as input file"
    import io
    global read, input
    f = io.StringIO(s.strip())

    def input():
        return bytes(f.readline(), "ascii")

    def read():
        return bytes(f.read(), "ascii")


USE_NUMBA = False
if (USE_NUMBA and sys.argv[-1] == 'ONLINE_JUDGE') or sys.argv[-1] == '-c':
    print("compiling")
    from numba.pycc import CC
    cc = CC('my_module')
    cc.export('solve', solve.__doc__.strip().split()[0])(solve)
    cc.compile()
    exit()
else:
    input = sys.stdin.buffer.readline
    read = sys.stdin.buffer.read

    if (USE_NUMBA and sys.argv[-1] != '-p') or sys.argv[-1] == "--numba":
        # -p: pure python mode
        # if not -p, import compiled module
        from my_module import solve  # pylint: disable=all
    elif sys.argv[-1] == "-t":
        print("testing")
        _test()
        sys.exit()
    elif sys.argv[-1] != '-p' and len(sys.argv) == 2:
        # input given as file
        input_as_file = open(sys.argv[1])
        input = input_as_file.buffer.readline
        read = input_as_file.buffer.read

    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


from collections import defaultdict
n, M = map(int, input().split())
ns = defaultdict(list)
for _ in range(n-1):
    u,v = map(int, input().split())
    ns[u-1].append(v-1)
    ns[v-1].append(u-1)

bs = {}
cump0 = defaultdict(list)
cump1 = defaultdict(list)
def sub(u, p):
    if (p,u) in bs:
        return bs[p,u]
    b = 1
    ps = []
    for v in ns[u]:
        if v==p:
            continue
        bb = sub(v, u)
        b *= (1+bb)
        b %= M
        ps.append(bb)
    v0 = 1
    v1 = 1
    l = len(ps)
    for i in range(l):
        cump0[u].append(v0)
        cump1[u].append(v1)
        v0 *= ps[i]+1
        v1 *= ps[l-1-i]+1
        v0%=M;v1%=M
    cump0[u].append(v0)
    cump1[u].append(v1)
        
    bs[p,u] = b % M
    return b

ans = [None]*n
def sub2(u, p):
    i = 0
    for v in ns[u]:
        if v==p:
            continue
        b1 = bs[p,u]
        b2 = bs[u,v]
        b3 = bs[u,p]
        if p>=0:
            bb = (cump0[u][i] * cump1[u][-(i+2)] * (1+b3)) % M
        else:
            bb = (cump0[u][i] * cump1[u][-(i+2)]) % M
        bs[v,u] = bb
        ans[v] = bs[u,v] * (1+bb) % M
        sub2(v,u)
        i += 1
        
sub(0, -1)
bs[0,-1] = 1
ans[0] = bs[-1,0]
sub2(0,-1)

# for u in range(n):
#     ans[u] = sub(u, -1)[1] % M
write("\n".join(map(str, ans)))

Submission status: Time Limit Exceeded

Solution code:
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


from collections import defaultdict
n, M = map(int, input().split())
ns = defaultdict(list)
for _ in range(n-1):
    u,v = map(int, input().split())
    ns[u-1].append(v-1)
    ns[v-1].append(u-1)

ws = {}
bs = {}
cump0 = defaultdict(list)
cump1 = defaultdict(list)
cums0 = defaultdict(list)
cums1 = defaultdict(list)
def sub(u, p):
    if (p,u) in ws:
        return ws[p,u], bs[p,u]
    w = 1
    b = 1
    ps = []
    for v in ns[u]:
        if v==p:
            continue
        ww,bb = sub(v, u)
        w += (bb-1)
        b *= (1+bb)
        b %= M
        ps.append(bb)
    v0 = 1
    v1 = 1
    s0 = 0
    s1 = 0
    l = len(ps)
    for i in range(l):
        cump0[u].append(v0)
        cump1[u].append(v1)
        cums0[u].append(s0)
        cums1[u].append(s1)
        v0 *= ps[i]+1
        v1 *= ps[l-1-i]+1
        s0 += ps[i]-1
        s1 += ps[l-1-i]-1
        v0%=M;v1%=M;s0%=M;s1%=M
    cump0[u].append(v0)
    cump1[u].append(v1)
    cums0[u].append(s0)
    cums1[u].append(s1)
        
    ws[p,u] = w % M
    bs[p,u] = b % M
    return w,b

ans = [None]*n
def sub2(u, p):
    i = 0
    for v in ns[u]:
        if v==p:
            continue
        w1, b1 = ws[p,u], bs[p,u]
        w2, b2 = ws[u,v], bs[u,v]
        w3, b3 = ws[u,p], bs[u,p]
        if p>=0:
            ww = cums0[u][i] + cums1[u][-(i+2)] + (b3-1)
            bb = (cump0[u][i] * cump1[u][-(i+2)] * (1+b3)) % M
        else:
            ww = cums0[u][i] + cums1[u][-(i+2)]
            bb = (cump0[u][i] * cump1[u][-(i+2)]) % M
        ws[v,u], bs[v,u] = ww,bb
        ans[v] = bs[u,v] * (1+bb) % M
        sub2(v,u)
        i += 1
        
sub(0, -1)
ws[0,-1] = 1
bs[0,-1] = 1
ans[0] = bs[-1,0]
sub2(0,-1)

# for u in range(n):
#     ans[u] = sub(u, -1)[1] % M
write("\n".join(map(str, ans)))

Submission status: Time Limit Exceeded

Solution code:
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")

from collections import defaultdict
n, M = map(int, input().split())
ns = defaultdict(set)
for _ in range(n-1):
    u,v = map(int, input().split())
    ns[u-1].add(v-1)
    ns[v-1].add(u-1)

ws = {}
bs = {}
def sub(u, p):
    if (u,p) in ws:
        return ws[u,p], bs[u,p]
    w = 1
    b = 1
    for v in ns[u]:
        if v==p:
            continue
        ww,bb = sub(v, u)
        w += (bb-1)
        b *= (1+bb)
        b %= M
    ws[u,p] = w % M
    bs[u,p] = b % M
    return w,b

ans = [None]*n

for u in range(n):
    ans[u] = sub(u, -1)[1] % M
write("\n".join(map(str, ans)))

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**9)

def solve():
    N, MOD = map(int, input().split())
    adjL = [[] for _ in range(N)]
    for _ in range(N-1):
        x, y = map(int, input().split())
        x, y = x-1, y-1
        adjL[x].append(y)
        adjL[y].append(x)

    dp = [[] for _ in range(N)]
    outdegs = [0] * N
    iPars = [-1] * N
    def dfsDP(v, vPar):
        outdeg = outdegs[v] = len(adjL[v])
        dp[v] = [0] * outdeg
        res = 1
        for i, v2 in enumerate(adjL[v]):
            if v2 == vPar:
                iPars[v] = i
                continue
            dp[v][i] = dfsDP(v2, v)
            res = res * dp[v][i] % MOD
        return (res + 1) % MOD

    anss = [0] * N
    def dfsAns(v, vPar, resPar):
        if vPar != -1:
            dp[v][iPars[v]] = resPar

        outdeg = outdegs[v]
        dpL = [1] * (outdeg+1)
        for i in range(outdeg):
            v2 = adjL[v][i]
            dpL[i+1] = dpL[i] * dp[v][i] % MOD
        dpR = [1] * (outdeg+1)
        for i in reversed(range(outdeg)):
            v2 = adjL[v][i]
            dpR[i] = dpR[i+1] * dp[v][i] % MOD
        anss[v] = dpL[-1]

        for i, v2 in enumerate(adjL[v]):
            if v2 == vPar: continue
            dfsAns(v2, v, (dpL[i] * dpR[i+1] + 1) % MOD)


    dfsDP(0, -1)
    dfsAns(0, -1, 0)

    print('\n'.join(map(str, anss)))


solve()

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict, deque


def read_int():
    return int(input().strip())


def read_ints():
    return list(map(int, input().strip().split(' ')))


def solve():
    """
    OPT[node] = OPT[child1]*OPT[child2]+1
    """
    G = defaultdict(list)
    N, M = read_ints()
    for _ in range(N-1):
        x, y = read_ints()
        G[x-1].append(y-1)
        G[y-1].append(x-1)
    VISIT, CALCULATE = 0, 1
    Q = [(VISIT, 0, None)]
    OPT = [1]*N
    while len(Q) != 0:
        t, node, parent = Q.pop()
        if t == VISIT:
            Q.append((CALCULATE, node, parent))
            for child in G[node]:
                if child != parent:
                    Q.append((VISIT, child, node))
        else:
            for child in G[node]:
                if child != parent:
                    OPT[node] *= (OPT[child]+1)
    Q = [(OPT[0], node, None)]
    while len(Q) != 0:
        T, node, parent = Q.pop()
        if parent is not None:
            OPT[node] *= T
        for child in G[node]:
            if child != parent:
                Q.append((OPT[node]//(OPT[child]+1)+1, child, node))
    for o in OPT:
        print(o%M)


if __name__ == '__main__':
    solve()

Submission status: Time Limit Exceeded

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

n, mod = map(int, input().split())
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)

ele_id = 1
# 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 + 1
merge_func = lambda a, b: a * b % mod


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)
# print(*dp, sep='\n')
dfs2(0, -1, ele_id)
for ans_i in ans:
    print(ans_i - 1)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**5+100)
from collections import *

def dfs1(v, pv):
    for nv in G[v]:
        if nv!=pv:
            st[v] *= dfs1(nv, v)+1
            st[v] %= M
    
    return st[v]
    
def dfs2(v, pv):
    cnt = 0
    l = []
    
    for nv in G[v]:
        if nv==pv:
            left = acc1[pv][idx[pv][v]]
            right = acc2[pv][idx[pv][v]+1]
            l.append((left*right+1)%M)
            rt[v] *= (left*right+1)%M
            rt[v] %= M
        else:
            l.append(st[nv]+1)
            rt[v] *= st[nv]+1
            rt[v] %= M
        
        idx[v][nv] = cnt
        cnt += 1
    
    acc1[v].append(1)
    
    for li in l:
        acc1[v].append(acc1[v][-1]*li%M)
    
    acc2[v].append(1)
    
    for li in l[::-1]:
        acc2[v].append(acc2[v][-1]*li%M)
    
    acc2[v].reverse()
    
    for nv in G[v]:
        if nv!=pv:
            dfs2(nv, v)
        
N, M = map(int, input().split())
G = [[] for _ in range(N)]

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

st = [1]*N
rt = [1]*N
dfs1(0, -1)

idx = defaultdict(lambda : defaultdict(int))
acc1 = defaultdict(list)
acc2 = defaultdict(list)
dfs2(0, -1)

for v in range(N):
    print(rt[v])

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(1000000)
def input():
    return sys.stdin.readline()
n, m = [int(i) for i in input().split()]
e = [[] for _ in range(n)]
for _ in range(n - 1):
    a, b = [int(i) - 1 for i in input().split()]
    e[a].append(b)
    e[b].append(a)
dp1 = [0] * n


def dfs1(i=0, r=-1):
    s = 1
    for j in e[i]:
        if j != r:
            s *= dfs1(j, i)
            s %= m
    dp1[i] = s
    return s + 1


dfs1()
dp2 = [0] * n
dp2[0] = dp1[0]


def dfs2(i=0, r=-1, s=1):
    a = [1]
    for j in e[i]:
        if j != r:
            a.append(a[-1] * (dp1[j]+1) % m)
    b = [1]
    for j in reversed(e[i]):
        if j != r:
            b.append(b[-1] * (dp1[j]+1) % m)
    b.reverse()

    k = 0
    for j in e[i]:
        if j != r:
            l = (a[k] * b[k + 1] * s + 1)%m
            dp2[j] = l * dp1[j] % m
            dfs2(j, i, l)
            k += 1


dfs2()
print("\n".join(map(str,dp2)))

Submission status: Time Limit Exceeded

Solution code:
# これは逆元を用いてやる方法
from collections import deque
import sys

input = sys.stdin.buffer.readline


n, m = map(int, input().split())
graph = [[] for _ in range(n + 1)]
for _ in range(n - 1):
    x, y = map(int, input().split())
    graph[x].append(y)
    graph[y].append(x)

# dp1は葉向きに見たときの塗り方
# 自身が黒い時、下の候補はどうなるか？
dp1 = [0] * (n + 1)
# dp2は根向きに見たときの塗り方
# 自身が黒い時、親側の候補はどうなるか？
dp2 = [0] * (n + 1)

# 1回目
start = 1
par = [-1] * (n + 1)
que = deque([start])
topo = []
while que:
    v = que.popleft()
    topo.append(v)
    for u in graph[v]:
        if par[v] == u:
            continue
        par[u] = v
        que.append(u)

for v in topo[::-1]:
    dp1[v] = 1
    for u in graph[v]:
        if u == par[v]:
            continue
        dp1[v] *= dp1[u] + 1

# dpは欲しい答えとしておく
# dp1とdp2から求める
dp = [0] * (n + 1)

for v in topo:
    # dp2の計算
    p = par[v]
    if p == -1:
        dp[v] = dp1[v]
        dp[v] %= m
        continue
    dp2[v] = dp1[p]
    dp2[v] //= dp1[v] + 1  # 親側に関して自身の関与は消す
    pp = par[p]  # 親の親
    if pp != -1:  # 親の親がいるならば
        dp2[v] *= dp2[p] + 1  # 白=1か黒=dp2[pp]か

    # dpの計算
    dp[v] = dp1[v] * (dp2[v] + 1)
    dp[v] %= m
print(*dp[1:], sep="\n")

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**5 + 1)
n, m = map(int, input().split())

graph = [[] for _ in range(n)]
for i in range(n - 1):
    a, b = map(lambda x: int(x) - 1, input().split())

    graph[a].append(b)
    graph[b].append(a)

rooted = [[] for _ in range(n)]
rev_rooted = [[] for _ in range(n)]
que = [(0, -1)]
while que:
    node, parent = que.pop()
    for child in graph[node]:
        if child != parent:
            que.append((child, node))
            rooted[node].append(child)
            rev_rooted[child].append(node)
            # print(node, child)

def mod(v):
    if v >= m:
        return v % m
    return v

dp = [None] * n
def dfs(node):
    if dp[node] is not None:
        return dp[node]

    pattern = 1 # 自身のみのパターン
    for child in rooted[node]:
        pattern = mod(pattern * (dfs(child) + 1))
    dp[node] = pattern
    return pattern

rev_dp = [None] * n
def rev_dfs(node):
    if rev_dp[node] is not None:
        return rev_dp[node]

    pattern = 1 # 自身のみのパターン
    if not rev_rooted[node]:
        pattern = 0
    else:
        parent = rev_rooted[node][0]
        pattern = mod(pattern * (rev_dfs(parent) + 1))
        for child in rooted[parent]:
            if child != node:
                pattern = mod(pattern * (dp[child] + 1))
    rev_dp[node] = pattern
    return pattern

# print("-----")
for i in range(n):
    dfs(i)
for i in range(n):
    print(mod(dp[i] * (rev_dfs(i) + 1)))

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**5 + 1)
n, m = map(int, input().split())

graph = [[] for _ in range(n)]
for i in range(n - 1):
    a, b = map(lambda x: int(x) - 1, input().split())

    graph[a].append(b)
    graph[b].append(a)

rooted = [[] for _ in range(n)]
rev_rooted = [[] for _ in range(n)]
que = [(0, -1)]
while que:
    node, parent = que.pop()
    for child in graph[node]:
        if child != parent:
            que.append((child, node))
            rooted[node].append(child)
            rev_rooted[child].append(node)

def mod(v):
    if v >= m:
        return v % m
    return v

dp = [None] * n
def dfs(node):
    if dp[node] is not None:
        return dp[node]

    pattern = 1 # 自身のみのパターン
    for child in rooted[node]:
        pattern = mod(pattern * (dfs(child) + 1))
    dp[node] = pattern
    return pattern

rev_dp = [None] * n
def rev_dfs(node):
    if rev_dp[node] is not None:
        return rev_dp[node]

    pattern = 1 # 自身のみのパターン
    if not rev_rooted[node]:
        pattern = 0
    for parent in rev_rooted[node]: # 親は0or1人
        pattern = mod(pattern * (rev_dfs(parent) + 1))
        for child in rooted[parent]:
            if child != node:
                pattern = mod(pattern * (dfs(child) + 1))
    rev_dp[node] = pattern
    return pattern

# print("-----")
for i in range(n):
    print(mod(dfs(i) * (rev_dfs(i) + 1)))

Submission status: Time Limit Exceeded

Solution code:
INF = 10 ** 11
import sys
sys.setrecursionlimit(100000000)

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

deg = [0] * N
dp = [None] * N
parents = [0] * N
ans = [0] * N

def dfs(v,p = -1):
    deg[v] = len(G[v])
    res = 1
    dp[v] = [0] * deg[v]
    for i,e in enumerate(G[v]):
        if e == p:
            parents[v] = i
            continue
        dp[v][i] = dfs(e,v)
        res *= dp[v][i] + 1
        res %= MOD
    return res

def bfs(v,res_p = 0,p = -1):
    if p != -1:
        dp[v][parents[v]] = res_p
    dpl = [1]*(deg[v] + 1)
    dpr = [1]*(deg[v] + 1)
    for i in range(deg[v]):
        dpl[i + 1] = dpl[i]*(dp[v][i] + 1)%MOD
    for i in range(deg[v] - 1,-1,-1):
        dpr[i] = dpr[i + 1]*(dp[v][i] + 1)%MOD
    ans[v] = dpr[0]
    for i in range(deg[v]):
        e = G[v][i]
        if e == p:
            continue
        bfs(e,dpl[i]*dpr[i + 1]%MOD,v)

dfs(0)
bfs(0)
print('\n'.join(map(str,ans)))