LuoTianyi and the Floating Islands (Easy Version) (Codeforces 1824B1)
Tags: Math, probabilities

This is the easy version of the problem. The only difference is that in this version $$$k\le\min(n,3)$$$. You can make hacks only if both versions of the problem are solved.  Chtholly and the floating islands. LuoTianyi now lives in a world with $$$n$$$ floating islands. The floating islands are connected by $$$n-1$$$ undirected air routes, and any two of them can reach each other by passing the routes. That means, the $$$n$$$ floating islands form a tree.One day, LuoTianyi wants to meet her friends: Chtholly, Nephren, William, .... Totally, she wants to meet $$$k$$$ people. She doesn't know the exact positions of them, but she knows that they are in pairwise distinct islands. She define an island is good if and only if the sum of the distances$$$^{\dagger}$$$ from it to the islands with $$$k$$$ people is the minimal among all the $$$n$$$ islands.Now, LuoTianyi wants to know that, if the $$$k$$$ people are randomly set in $$$k$$$ distinct of the $$$n$$$ islands, then what is the expect number of the good islands? You just need to tell her the expect number modulo $$$10^9+7$$$.$$$^{\dagger}$$$The distance between two islands is the minimum number of air routes you need to take to get from one island to the other.

Input: The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1\le k \le \min(n,3), 1\le n \le 2\cdot 10^5$$$) — the number of the islands and people respectively.Next $$$n−1$$$ lines describe the air routes. The $$$i$$$-th of them contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \le u_i,v_i \le n, u_i \neq v_i$$$) — the islands connected by the $$$i$$$-th air route.

Output: Print a single integer — the expect number of the good islands modulo $$$10^9 + 7$$$.Formally, let $$$M = 10^9 + 7$$$. It can be shown that the answer can be expressed as an irreducible fraction $$$\frac{p}{q}$$$, where $$$p$$$ and $$$q$$$ are integers and $$$q \not \equiv 0$$$ ($$$\operatorname{mod} M$$$). Output the integer equal to $$$p \cdot q^{-1}$$$ $$$\operatorname{mod} M$$$. In other words, output such an integer $$$x$$$ that $$$0 \le x < M$$$ and $$$x \cdot q \equiv p$$$ ($$$\operatorname{mod} M$$$).

Note: In the first example the air routes form the following tree:   If the people are in the islands $$$1$$$ and $$$2$$$, then islands $$$1$$$ and $$$2$$$ will be good.The sum of the distances from island $$$1$$$ or $$$2$$$ to all the people is $$$1+0=1$$$, which is the minimal. While the sum of the distances from island $$$3$$$ to all the people is $$$2+1=3$$$, which is greater than $$$1$$$.Like this, when the people are in island $$$1$$$ and $$$3$$$, then islands $$$1,2$$$ and $$$3$$$ will be good.When the people are in islands $$$1$$$ and $$$4$$$, then islands $$$1,2,3$$$ and $$$4$$$ will be good.When the people are in islands $$$2$$$ and $$$3$$$, then islands $$$2$$$ and $$$3$$$ will be good.When the people are in islands $$$2$$$ and $$$4$$$, then islands $$$2,3$$$ and $$$4$$$ will be good.When the people are in islands $$$3$$$ and $$$4$$$, then islands $$$3$$$ and $$$4$$$ will be good.So the expect of the number of the good islands is $$$\frac{16}{6}$$$, which equals to $$$666666674$$$ modulo $$$10^9+7$$$.In the second example the air routes form the following tree:  There is always the only good island, so the expected number is $$$1$$$.

Sample Inputs:
4 2
1 2
2 3
3 4

5 1
1 2
2 3
3 4
3 5

Sample Outputs:
666666674

1

Solution (Python):
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def make_graph(n, m):
    (x, s) = ([0] * (2 * m), [0] * (n + 3))
    for i in range(0, 2 * m, 2):
        (u, v) = map(int, input().split())
        s[u + 2] += 1
        s[v + 2] += 1
        (x[i], x[i + 1]) = (u, v)
    for i in range(3, n + 3):
        s[i] += s[i - 1]
    G = [0] * (2 * m)
    for i in range(2 * m):
        j = x[i] + 1
        G[s[j]] = x[i ^ 1]
        s[j] += 1
    return (G, s)

def bfs(s):
    q = [s]
    dist = [inf] * (n + 1)
    dist[s] = 0
    parent = [-1] * (n + 1)
    for k in range(n):
        i = q[k]
        di = dist[i]
        for v in range(s0[i], s0[i + 1]):
            j = G[v]
            if dist[j] == inf:
                q.append(j)
                dist[j] = di + 1
                parent[j] = i
    return (q, dist, parent)
(n, k) = map(int, input().split())
(G, s0) = make_graph(n, n - 1)
inf = pow(10, 9) + 1
mod = pow(10, 9) + 7
if k % 2:
    ans = 1
else:
    (p, dist, parent) = bfs(1)
    cnt = [1] * (n + 1)
    for i in p[::-1][:-1]:
        cnt[parent[i]] += cnt[i]
    dp = [0] * (n + 1)
    dp[1] = (sum(dist[1:]) + n - 1) % mod
    for i in p[1:]:
        dp[i] = (dp[parent[i]] + n - 2 * cnt[i]) % mod
    inv = pow(n * (n - 1), mod - 2, mod)
    ans = sum(dp) % mod * inv % mod
print(ans)

Solution (Python):
import io, os
from collections import deque
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def fastfrac(a, b, M):
    invb = pow(b, M - 2, M)
    return a * invb % M

def getdistance(neigh):
    n = len(neigh)
    children = [[] for _ in range(n)]
    parent = [-2] * n
    parent[0] = -1
    layer = [0] * n
    subnum = [0] * n
    ans = [0] * n
    seq = []
    queue = deque()
    queue.append(0)
    while queue:
        index = queue.popleft()
        seq.append(index)
        for nextindex in neigh[index]:
            if parent[nextindex] > -2:
                continue
            parent[nextindex] = index
            layer[nextindex] = layer[index] + 1
            ans[0] += layer[nextindex]
            children[index].append(nextindex)
            queue.append(nextindex)
    for index in seq[::-1]:
        subnum[index] = 1
        for nextindex in children[index]:
            subnum[index] += subnum[nextindex]
    for index in seq[1:]:
        ans[index] = ans[parent[index]] + n - 2 * subnum[index]
    return ans

def main(t):
    (n, k) = map(int, input().split())
    neigh = [[] for _ in range(n)]
    for i in range(n - 1):
        (u, v) = map(int, input().split())
        neigh[u - 1].append(v - 1)
        neigh[v - 1].append(u - 1)
    if k == 1 or k == 3:
        print(1)
        return
    distances = getdistance(neigh)
    M = 10 ** 9 + 7
    ans = fastfrac(sum(distances), n * (n - 1), M)
    ans = (ans + 1) % M
    print(ans)
T = 1
t = 1
while t <= T:
    main(t)
    t += 1

Solution (Python):
import os
import sys
import random
import threading
from copy import deepcopy
from io import BytesIO, IOBase
from types import GeneratorType
from functools import lru_cache, reduce
from bisect import bisect_left, bisect_right
from collections import Counter, defaultdict, deque
from itertools import accumulate, combinations, permutations
from heapq import nsmallest, nlargest, heapify, heappop, heappush
from typing import Generic, Iterable, Iterator, TypeVar, Union, List

def debug(func):

    def wrapper(*args, **kwargs):
        print('----------------')
        res = func(*args, **kwargs)
        print('----------------')
        return res
    return wrapper

def bootstrap(f, stack=[]):

    def wrappedfunc(*args, **kwargs):
        if stack:
            return f(*args, **kwargs)
        else:
            to = f(*args, **kwargs)
            while True:
                if type(to) is GeneratorType:
                    stack.append(to)
                    to = next(to)
                else:
                    stack.pop()
                    if not stack:
                        break
                    to = stack[-1].send(to)
            return to
    return wrappedfunc

class SegTree:
    """"""

    def __init__(self, f1, f2, l, r, v=0):
        """"""
        self.ans = f2(v, r - l)
        self.f1 = f1
        self.f2 = f2
        self.l = l
        self.r = r
        self.v = v
        self.lazy_tag = 0
        self.left = None
        self.right = None

    @property
    def mid_h(self):
        return (self.l + self.r) // 2

    def create_subtrees(self):
        midh = self.mid_h
        if not self.left and midh > self.l:
            self.left = SegTree(self.f1, self.f2, self.l, midh)
        if not self.right:
            self.right = SegTree(self.f1, self.f2, midh, self.r)

    def init_seg(self, M):
        """"""
        m0 = M[0]
        self.lazy_tag = 0
        for a in M:
            if a != m0:
                break
        else:
            self.v = m0
            self.ans = self.f2(m0, len(M))
            return self.ans
        self.v = '#'
        midh = self.mid_h
        self.create_subtrees()
        self.ans = self.f1(self.left.init_seg(M[:midh - self.l]), self.right.init_seg(M[midh - self.l:]))
        return self.ans

    def cover_seg(self, l, r, v):
        """"""
        if self.v == v or l >= self.r or r <= self.l:
            return self.ans
        if l <= self.l and r >= self.r:
            self.v = v
            self.lazy_tag = 0
            self.ans = self.f2(v, self.r - self.l)
            return self.ans
        self.create_subtrees()
        if self.v != '#':
            if self.left:
                self.left.v = self.v
                self.left.ans = self.f2(self.v, self.left.r - self.left.l)
            if self.right:
                self.right.v = self.v
                self.right.ans = self.f2(self.v, self.right.r - self.right.l)
            self.v = '#'
        self.ans = self.f1(self.left.cover_seg(l, r, v), self.right.cover_seg(l, r, v))
        return self.ans

    def inc_seg(self, l, r, v):
        """"""
        if v == 0 or l >= self.r or r <= self.l:
            return self.ans
        if l <= self.l and r >= self.r:
            if self.v == '#':
                self.lazy_tag += v
            else:
                self.v += v
            self.ans += self.f2(v, self.r - self.l)
            return self.ans
        self.create_subtrees()
        if self.v != '#':
            self.left.v = self.v
            self.left.ans = self.f2(self.v, self.left.r - self.left.l)
            self.right.v = self.v
            self.right.ans = self.f2(self.v, self.right.r - self.right.l)
            self.v = '#'
        self.pushdown()
        self.ans = self.f1(self.left.inc_seg(l, r, v), self.right.inc_seg(l, r, v))
        return self.ans

    def inc_idx(self, idx, v):
        """"""
        if v == 0 or idx >= self.r or idx < self.l:
            return self.ans
        if idx == self.l == self.r - 1:
            self.v += v
            self.ans += self.f2(v, 1)
            return self.ans
        self.create_subtrees()
        if self.v != '#':
            self.left.v = self.v
            self.left.ans = self.f2(self.v, self.left.r - self.left.l)
            self.right.v = self.v
            self.right.ans = self.f2(self.v, self.right.r - self.right.l)
            self.v = '#'
        self.pushdown()
        self.ans = self.f1(self.left.inc_idx(idx, v), self.right.inc_idx(idx, v))
        return self.ans

    def pushdown(self):
        if self.lazy_tag != 0:
            if self.left:
                if self.left.v != '#':
                    self.left.v += self.lazy_tag
                    self.left.lazy_tag = 0
                else:
                    self.left.lazy_tag += self.lazy_tag
                self.left.ans += self.f2(self.lazy_tag, self.left.r - self.left.l)
            if self.right:
                if self.right.v != '#':
                    self.right.v += self.lazy_tag
                    self.right.lazy_tag = 0
                else:
                    self.right.lazy_tag += self.lazy_tag
                self.right.ans += self.f2(self.lazy_tag, self.right.r - self.right.l)
            self.lazy_tag = 0

    def query(self, l, r):
        """"""
        if l >= r:
            return 0
        if l <= self.l and r >= self.r:
            return self.ans
        if self.v != '#':
            return self.f2(self.v, min(self.r, r) - max(self.l, l))
        midh = self.mid_h
        anss = []
        if l < midh:
            anss.append(self.left.query(l, r))
        if r > midh:
            anss.append(self.right.query(l, r))
        return reduce(self.f1, anss)

class SortedList:

    def __init__(self, iterable=[], _load=200):
        """"""
        values = sorted(iterable)
        self._len = _len = len(values)
        self._load = _load
        self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
        self._list_lens = [len(_list) for _list in _lists]
        self._mins = [_list[0] for _list in _lists]
        self._fen_tree = []
        self._rebuild = True

    def _fen_build(self):
        """"""
        self._fen_tree[:] = self._list_lens
        _fen_tree = self._fen_tree
        for i in range(len(_fen_tree)):
            if i | i + 1 < len(_fen_tree):
                _fen_tree[i | i + 1] += _fen_tree[i]
        self._rebuild = False

    def _fen_update(self, index, value):
        """"""
        if not self._rebuild:
            _fen_tree = self._fen_tree
            while index < len(_fen_tree):
                _fen_tree[index] += value
                index |= index + 1

    def _fen_query(self, end):
        """"""
        if self._rebuild:
            self._fen_build()
        _fen_tree = self._fen_tree
        x = 0
        while end:
            x += _fen_tree[end - 1]
            end &= end - 1
        return x

    def _fen_findkth(self, k):
        """"""
        _list_lens = self._list_lens
        if k < _list_lens[0]:
            return (0, k)
        if k >= self._len - _list_lens[-1]:
            return (len(_list_lens) - 1, k + _list_lens[-1] - self._len)
        if self._rebuild:
            self._fen_build()
        _fen_tree = self._fen_tree
        idx = -1
        for d in reversed(range(len(_fen_tree).bit_length())):
            right_idx = idx + (1 << d)
            if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
                idx = right_idx
                k -= _fen_tree[idx]
        return (idx + 1, k)

    def _delete(self, pos, idx):
        """"""
        _lists = self._lists
        _mins = self._mins
        _list_lens = self._list_lens
        self._len -= 1
        self._fen_update(pos, -1)
        del _lists[pos][idx]
        _list_lens[pos] -= 1
        if _list_lens[pos]:
            _mins[pos] = _lists[pos][0]
        else:
            del _lists[pos]
            del _list_lens[pos]
            del _mins[pos]
            self._rebuild = True

    def _loc_left(self, value):
        """"""
        if not self._len:
            return (0, 0)
        _lists = self._lists
        _mins = self._mins
        (lo, pos) = (-1, len(_lists) - 1)
        while lo + 1 < pos:
            mi = lo + pos >> 1
            if value <= _mins[mi]:
                pos = mi
            else:
                lo = mi
        if pos and value <= _lists[pos - 1][-1]:
            pos -= 1
        _list = _lists[pos]
        (lo, idx) = (-1, len(_list))
        while lo + 1 < idx:
            mi = lo + idx >> 1
            if value <= _list[mi]:
                idx = mi
            else:
                lo = mi
        return (pos, idx)

    def _loc_right(self, value):
        """"""
        if not self._len:
            return (0, 0)
        _lists = self._lists
        _mins = self._mins
        (pos, hi) = (0, len(_lists))
        while pos + 1 < hi:
            mi = pos + hi >> 1
            if value < _mins[mi]:
                hi = mi
            else:
                pos = mi
        _list = _lists[pos]
        (lo, idx) = (-1, len(_list))
        while lo + 1 < idx:
            mi = lo + idx >> 1
            if value < _list[mi]:
                idx = mi
            else:
                lo = mi
        return (pos, idx)

    def add(self, value):
        """"""
        _load = self._load
        _lists = self._lists
        _mins = self._mins
        _list_lens = self._list_lens
        self._len += 1
        if _lists:
            (pos, idx) = self._loc_right(value)
            self._fen_update(pos, 1)
            _list = _lists[pos]
            _list.insert(idx, value)
            _list_lens[pos] += 1
            _mins[pos] = _list[0]
            if _load + _load < len(_list):
                _lists.insert(pos + 1, _list[_load:])
                _list_lens.insert(pos + 1, len(_list) - _load)
                _mins.insert(pos + 1, _list[_load])
                _list_lens[pos] = _load
                del _list[_load:]
                self._rebuild = True
        else:
            _lists.append([value])
            _mins.append(value)
            _list_lens.append(1)
            self._rebuild = True

    def discard(self, value):
        """"""
        _lists = self._lists
        if _lists:
            (pos, idx) = self._loc_right(value)
            if idx and _lists[pos][idx - 1] == value:
                self._delete(pos, idx - 1)

    def remove(self, value):
        """"""
        _len = self._len
        self.discard(value)
        if _len == self._len:
            raise ValueError('{0!r} not in list'.format(value))

    def pop(self, index=-1):
        """"""
        (pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
        value = self._lists[pos][idx]
        self._delete(pos, idx)
        return value

    def bisect_left(self, value):
        """"""
        (pos, idx) = self._loc_left(value)
        return self._fen_query(pos) + idx

    def bisect_right(self, value):
        """"""
        (pos, idx) = self._loc_right(value)
        return self._fen_query(pos) + idx

    def count(self, value):
        """"""
        return self.bisect_right(value) - self.bisect_left(value)

    def __len__(self):
        """"""
        return self._len

    def __getitem__(self, index):
        """"""
        (pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
        return self._lists[pos][idx]

    def __delitem__(self, index):
        """"""
        (pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
        self._delete(pos, idx)

    def __contains__(self, value):
        """"""
        _lists = self._lists
        if _lists:
            (pos, idx) = self._loc_left(value)
            return idx < len(_lists[pos]) and _lists[pos][idx] == value
        return False

    def __iter__(self):
        """"""
        return (value for _list in self._lists for value in _list)

    def __reversed__(self):
        """"""
        return (value for _list in reversed(self._lists) for value in reversed(_list))

    def __repr__(self):
        """"""
        return 'SortedList({0})'.format(list(self))
T = TypeVar('T')

class SortedSet(Generic[T]):
    BUCKET_RATIO = 50
    REBUILD_RATIO = 170

    def _build(self, a=None) -> None:
        """"""
        if a is None:
            a = list(self)
        size = self.size = len(a)
        bucket_size = int(math.ceil(math.sqrt(size / self.BUCKET_RATIO)))
        self.a = [a[size * i // bucket_size:size * (i + 1) // bucket_size] for i in range(bucket_size)]

    def __init__(self, a: Iterable[T]=[]) -> None:
        """"""
        a = list(a)
        if not all((a[i] < a[i + 1] for i in range(len(a) - 1))):
            a = sorted(set(a))
        self._build(a)

    def __iter__(self) -> Iterator[T]:
        for i in self.a:
            for j in i:
                yield j

    def __reversed__(self) -> Iterator[T]:
        for i in reversed(self.a):
            for j in reversed(i):
                yield j

    def __len__(self) -> int:
        return self.size

    def __repr__(self) -> str:
        return 'SortedSet' + str(self.a)

    def __str__(self) -> str:
        s = str(list(self))
        return '{' + s[1:len(s) - 1] + '}'

    def _find_bucket(self, x: T) -> List[T]:
        """"""
        for a in self.a:
            if x <= a[-1]:
                return a
        return a

    def __contains__(self, x: T) -> bool:
        if self.size == 0:
            return False
        a = self._find_bucket(x)
        i = bisect_left(a, x)
        return i != len(a) and a[i] == x

    def add(self, x: T) -> bool:
        """"""
        if self.size == 0:
            self.a = [[x]]
            self.size = 1
            return True
        a = self._find_bucket(x)
        i = bisect_left(a, x)
        if i != len(a) and a[i] == x:
            return False
        a.insert(i, x)
        self.size += 1
        if len(a) > len(self.a) * self.REBUILD_RATIO:
            self._build()
        return True

    def discard(self, x: T) -> bool:
        """"""
        if self.size == 0:
            return False
        a = self._find_bucket(x)
        i = bisect_left(a, x)
        if i == len(a) or a[i] != x:
            return False
        a.pop(i)
        self.size -= 1
        if len(a) == 0:
            self._build()
        return True

    def lt(self, x: T) -> Union[T, None]:
        """"""
        for a in reversed(self.a):
            if a[0] < x:
                return a[bisect_left(a, x) - 1]

    def le(self, x: T) -> Union[T, None]:
        """"""
        for a in reversed(self.a):
            if a[0] <= x:
                return a[bisect_right(a, x) - 1]

    def gt(self, x: T) -> Union[T, None]:
        """"""
        for a in self.a:
            if a[-1] > x:
                return a[bisect_right(a, x)]

    def ge(self, x: T) -> Union[T, None]:
        """"""
        for a in self.a:
            if a[-1] >= x:
                return a[bisect_left(a, x)]

    def __getitem__(self, x: int) -> T:
        """"""
        if x < 0:
            x += self.size
        if x < 0:
            raise IndexError
        for a in self.a:
            if x < len(a):
                return a[x]
            x -= len(a)
        raise IndexError

    def index(self, x: T) -> int:
        """"""
        ans = 0
        for a in self.a:
            if a[-1] >= x:
                return ans + bisect_left(a, x)
            ans += len(a)
        return ans

    def index_right(self, x: T) -> int:
        """"""
        ans = 0
        for a in self.a:
            if a[-1] > x:
                return ans + bisect_right(a, x)
            ans += len(a)
        return ans
BUFSIZE = 4096

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = 'x' in file.mode or 'r' not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            (self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b'\n') + (not b)
            ptr = self.buffer.tell()
            (self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            (self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode('ascii'))
        self.read = lambda : self.buffer.read().decode('ascii')
        self.readline = lambda : self.buffer.readline().decode('ascii')
sys.stdin = IOWrapper(sys.stdin)
sys.stdout = IOWrapper(sys.stdout)
input = lambda : sys.stdin.readline().rstrip('\r\n')

def I():
    return input()

def II():
    return int(input())

def MI():
    return map(int, input().split())

def LI():
    return list(input().split())

def LII():
    return list(map(int, input().split()))

def GMI():
    return map(lambda x: int(x) - 1, input().split())

def LGMI():
    return list(map(lambda x: int(x) - 1, input().split()))
MOD = 10 ** 9 + 7

def get_inverse(a, b):
    (old_s, s) = (1, 0)
    (old_r, r) = (a, b)
    if b == 0:
        return -1
    else:
        while r != 0:
            q = old_r // r
            (old_r, r) = (r, old_r - q * r)
            (old_s, s) = (s, old_s - q * s)
    return old_s % b

def solve():
    (n, k) = LII()
    d = defaultdict(list)
    for _ in range(n - 1):
        (u, v) = LII()
        d[u - 1].append(v - 1)
        d[v - 1].append(u - 1)
    ans = 1
    children = [0] * n

    @bootstrap
    def dfs(cur, pa):
        res = 1
        for nxt in d[cur]:
            if nxt != pa:
                res += (yield dfs(nxt, cur))
        children[cur] = res
        yield res
    fact = [1] * (n + 1)
    for i in range(1, n + 1):
        fact[i] = fact[i - 1] * i % MOD
    inverse = [0] * (n + 1)
    inverse[n] = pow(fact[n], MOD - 2, MOD)
    for i in range(n, 0, -1):
        inverse[i - 1] = inverse[i] * i % MOD

    def comb(n: int, m: int, MOD=MOD) -> int:
        if m < 0 or m > n:
            return 0
        return fact[n] * inverse[m] % MOD * inverse[n - m] % MOD
    if k % 2 == 0:
        dfs(0, -1)
        inv = get_inverse(comb(n, k), MOD)
        for size in children:
            if size >= k // 2 and n - size >= k // 2:
                a = comb(size, k // 2)
                b = comb(n - size, k // 2)
                ans += a * b * inv
                ans %= MOD
    return print(ans)
if __name__ == '__main__':
    for _ in range(1):
        solve()