LuoTianyi and the Floating Islands (Hard Version) (Codeforces 1825D2)
Tags: Math, trees

This is the hard version of the problem. The only difference is that in this version $$$k\le n$$$. 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 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:  We can see that there is one person in each island, and only the island $$$3$$$ is good. So the expect number is $$$1$$$.

Sample Inputs:
4 2
1 2
2 3
3 4

5 5
1 2
2 3
3 4
3 5

Sample Outputs:
666666674

1

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

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

def readInt():
    return int(input())

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

def readStr():
    return input().strip()

def nCr(n, r):
    return 0 if n < r else fac[n] * pow(fac[r], m - 2, m) * pow(fac[n - r], m - 2, m) % m

def solve():
    (n, k) = readInts()
    edges = []
    graph = [[] for _ in range(n + 1)]
    for _ in range(n - 1):
        (u, v) = readInts()
        graph[u].append(v)
        graph[v].append(u)
        edges.append((u, v))
    if k % 2:
        return 1
    m = 10 ** 9 + 7
    st = [(1, 0)]
    par = {1: -1}
    vis = [False] * (n + 1)
    size = [1] * (n + 1)
    while st:
        (node, dis) = st[-1]
        if vis[node]:
            (v, _) = st.pop()
            if node == 1:
                continue
            size[par[v]] += size[node]
            continue
        vis[node] = True
        for nei in graph[node]:
            if nei in par:
                continue
            par[nei] = node
            st.append((nei, dis + 1))
    ans = 0
    for i in range(1, n + 1):
        cnt = size[i]
        ans += nCr(cnt, k // 2) * nCr(n - cnt, k // 2)
    return (ans * pow(nCr(n, k), m - 2, m) % m + 1) % m
v = 2 * 10 ** 5 + 1
fac = [1] * v
m = 10 ** 9 + 7
for i in range(2, v):
    fac[i] = i * fac[i - 1] % m
print(solve())

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

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

def readInt():
    return int(input())

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

def readStr():
    return input().strip()

def nCr(n, r):
    return 0 if n < r else fac[n] * pow(fac[r], m - 2, m) * pow(fac[n - r], m - 2, m) % m

def solve():
    (n, k) = readInts()
    edges = []
    graph = [[] for _ in range(n + 1)]
    for _ in range(n - 1):
        (u, v) = readInts()
        graph[u].append(v)
        graph[v].append(u)
        edges.append((u, v))
    if k % 2:
        return 1
    m = 10 ** 9 + 7
    st = [(1, 0)]
    par = {1: -1}
    vis = [False] * (n + 1)
    size = [1] * (n + 1)
    while st:
        (node, dis) = st[-1]
        if vis[node]:
            (v, _) = st.pop()
            if node == 1:
                continue
            size[par[v]] += size[node]
            continue
        vis[node] = True
        for nei in graph[node]:
            if nei in par:
                continue
            par[nei] = node
            st.append((nei, dis + 1))
    ans = 0
    for (x, y) in edges:
        cnt = min(size[x], size[y])
        ans += nCr(cnt, k // 2) * nCr(n - cnt, k // 2)
    return (ans * pow(nCr(n, k), m - 2, m) % m + 1) % m
v = 2 * 10 ** 5 + 1
fac = [1] * v
m = 10 ** 9 + 7
for i in range(2, v):
    fac[i] = i * fac[i - 1] % m
print(solve())

Solution (Python):
MOD = 10 ** 9 + 7
U = 2 * 10 ** 5
fact = [1] * (U + 1)
invfact = [1] * (U + 1)
for i in range(1, U + 1):
    fact[i] = fact[i - 1] * i % MOD
invfact[U] = pow(fact[U], MOD - 2, MOD)
for i in range(U - 1, -1, -1):
    invfact[i] = invfact[i + 1] * (i + 1) % MOD

def nCr(n, r):
    if n < 0 or r < 0 or n - r < 0:
        return 0
    return fact[n] * invfact[r] % MOD * invfact[n - r] % MOD
(N, K) = map(int, input().split())
G = [[] for _ in range(N)]
for _ in range(N - 1):
    (a, b) = map(int, input().split())
    (a, b) = (a - 1, b - 1)
    G[a].append(b)
    G[b].append(a)
if K % 2:
    print(1)
else:
    cnt = [0] * N
    par = [-1] * N
    st = [0]
    ans = 0
    while st:
        cur = st.pop()
        if cur >= 0:
            st.append(~cur)
            for nxt in G[cur]:
                if par[cur] == nxt:
                    continue
                par[nxt] = cur
                st.append(nxt)
        else:
            cur = ~cur
            T = 1
            for nxt in G[cur]:
                if par[cur] == nxt:
                    continue
                T += cnt[nxt]
            ans += nCr(T, K // 2) * nCr(N - T, K // 2) % MOD
            ans %= MOD
            cnt[cur] = T
    print((1 + ans * pow(nCr(N, K), MOD - 2, MOD)) % MOD)