Tree Array (Codeforces 1540B)
Tags: Math, probabilities

You are given a tree consisting of $$$n$$$ nodes. You generate an array from the tree by marking nodes one by one.Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree. After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked nodes with at least one edge to a marked node. It can be shown that the process marks all nodes in the tree. The final array $$$a$$$ is the list of the nodes' labels in order of the time each node was marked.Find the expected number of inversions in the array that is generated by the tree and the aforementioned process.The number of inversions in an array $$$a$$$ is the number of pairs of indices $$$(i, j)$$$ such that $$$i < j$$$ and $$$a_i > a_j$$$. For example, the array $$$[4, 1, 3, 2]$$$ contains $$$4$$$ inversions: $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(1, 4)$$$, $$$(3, 4)$$$.

Input: The first line contains a single integer $$$n$$$ ($$$2 \le n \le 200$$$) — the number of nodes in the tree.The next $$$n - 1$$$ lines each contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le n$$$; $$$x \neq y$$$), denoting an edge between node $$$x$$$ and $$$y$$$.It's guaranteed that the given edges form a tree.

Output: Output the expected number of inversions in the generated array 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 \pmod{M}$$$. Output the integer equal to $$$p \cdot q^{-1} \bmod M$$$. In other words, output such an integer $$$x$$$ that $$$0 \le x < M$$$ and $$$x \cdot q \equiv p \pmod{M}$$$.

Note: This is the tree from the first sample:  For the first sample, the arrays are almost fixed. If node $$$2$$$ is chosen initially, then the only possible array is $$$[2, 1, 3]$$$ ($$$1$$$ inversion). If node $$$3$$$ is chosen initially, then the only possible array is $$$[3, 1, 2]$$$ ($$$2$$$ inversions). If node $$$1$$$ is chosen initially, the arrays $$$[1, 2, 3]$$$ ($$$0$$$ inversions) and $$$[1, 3, 2]$$$ ($$$1$$$ inversion) are the only possibilities and equiprobable. In total, the expected number of inversions is $$$\frac{1}{3}\cdot 1 + \frac{1}{3} \cdot 2 + \frac{1}{3} \cdot (\frac{1}{2} \cdot 0 + \frac{1}{2} \cdot 1) = \frac{7}{6}$$$. $$$166666669 \cdot 6 = 7 \pmod {10^9 + 7}$$$, so the answer is $$$166666669$$$.This is the tree from the second sample:   This is the tree from the third sample:   

Sample Inputs:
3
1 2
1 3

6
2 1
2 3
6 1
1 4
2 5

5
1 2
1 3
1 4
2 5

Sample Outputs:
166666669

500000009

500000007

Solution (Python):
import sys
input = sys.stdin.buffer.readline
maxn = 300
mod = 10 ** 9 + 7
fac = [0] * (maxn + 1)
inv_fac = [0] * (maxn + 1)
fac[0] = 1
for i in range(1, maxn + 1):
    fac[i] = fac[i - 1] * i % mod
inv_fac[maxn] = pow(fac[maxn], mod - 2, mod)
for i in range(maxn - 1, -1, -1):
    inv_fac[i] = inv_fac[i + 1] * (i + 1) % mod

def choose(n, k):
    if k > n:
        return 0
    return fac[n] * inv_fac[k] * inv_fac[n - k] % mod
inv_p = [0] * 300
inv_p[1] = inv_fac[2]
for i in range(2, 300):
    inv_p[i] = inv_p[1] * inv_p[i - 1] % mod
n = int(input())
adj = [[] for i in range(n + 1)]
for i in range(n - 1):
    (a, b) = map(int, input().split())
    adj[a].append(b)
    adj[b].append(a)
ans = 0
line_prob = [[0] * (n + 1) for i in range(n + 1)]
for j in range(1, n + 1):
    tot = 0
    for i in range(n + 1 - j):
        tot += choose(j - 1 + i, i) * inv_p[j - 1 + i + 1] % mod
        line_prob[i + 1][j] = tot
''
for root in range(1, n + 1):
    size_of_sub = [0] * (n + 1)
    s = [root]
    vis = [0] * (n + 1)
    par = [0] * (n + 1)
    while s:
        c = s[-1]
        if not vis[c]:
            vis[c] = 1
            for ne in adj[c]:
                if not vis[ne]:
                    par[ne] = c
                    s.append(ne)
        else:
            size_of_sub[c] += 1
            size_of_sub[par[c]] += size_of_sub[c]
            s.pop()
    s = [root]
    vis = [0] * (n + 1)
    path = []
    while s:
        c = s[-1]
        if not vis[c]:
            vis[c] = 1
            if len(path):
                path[-1] -= size_of_sub[c]
            path.append(size_of_sub[c])
            if c > root:
                ln = len(path) - 1
                for depth in range(1, ln):
                    ans = ans + path[depth] * line_prob[depth][ln - depth] % mod
                ans = (ans + size_of_sub[c]) % mod
            for ne in adj[c]:
                if not vis[ne]:
                    s.append(ne)
        else:
            if len(path) >= 2:
                path[-2] += path[-1]
            path.pop()
            s.pop()
print(ans * pow(n, mod - 2, mod) % mod)

Solution (Python):
import sys
input = lambda : sys.stdin.readline().rstrip()
from collections import deque
mod = 10 ** 9 + 7
N = int(input())
E = []
for _ in range(N - 1):
    (x, y) = map(int, input().split())
    (x, y) = (x - 1, y - 1)
    E.append((x, y))
pre = [1]
PA = [pre]
for i in range(N + 2):
    ne = [0] * (i + 2)
    for (j, a) in enumerate(pre):
        ne[j] = (ne[j] + a) % mod
        ne[j + 1] = (ne[j + 1] + a) % mod
    PA.append(ne)
    pre = ne
for pa in PA:
    for i in range(len(pa) - 1):
        pa[i + 1] = (pa[i + 1] + pa[i]) % mod
i2 = mod + 1 >> 1
poi2 = [1]
for _ in range(N + 5):
    poi2.append(poi2[-1] * i2 % mod)
iN = pow(N, mod - 2, mod)
ans = 0
for i0 in range(N):
    X = [[] for i in range(N)]
    for (x, y) in E:
        X[x].append(y)
        X[y].append(x)
    P = [-1] * N
    Q = deque([i0])
    R = []
    D = [0] * N
    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)
                D[a] = D[i] + 1
    size = [1] * N
    for j in R[1:][::-1]:
        size[P[j]] += size[j]
    for j in R:
        if j <= i0:
            continue
        d = D[j]
        ans = ans + size[j] * iN
        k = j
        while P[k] != i0:
            p = P[k]
            s = size[p] - size[k]
            ans = (ans + s * PA[d - 1][D[p] - 1] % mod * iN % mod * poi2[d - 1]) % mod
            k = p
print(ans)

Solution (Python):
def solve():
    MOD = 10 ** 9 + 7
    inv2 = (MOD + 1) // 2
    n = int(input())
    dist = [[n] * n for i in range(n)]
    for i in range(n):
        dist[i][i] = 0
    for i in range(n - 1):
        (x, y) = map(int, input().split())
        x -= 1
        y -= 1
        dist[x][y] = dist[y][x] = 1
    for k in range(n):
        for i in range(n):
            for j in range(n):
                dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
    dp = [[0] * n for i in range(n)]
    dp[0] = [1] * n
    for i in range(1, n):
        for j in range(1, n):
            dp[i][j] = (dp[i - 1][j] + dp[i][j - 1]) * inv2 % MOD
    ans = 0
    for i in range(n):
        for j in range(i):
            for k in range(n):
                (di, dj, d) = (dist[i][k], dist[j][k], dist[i][j])
                ans = (ans + dp[(di + d - dj) // 2][(dj + d - di) // 2]) % MOD
    return ans * pow(n, MOD - 2, MOD) % MOD
import sys
input = lambda : sys.stdin.readline().rstrip()
print(solve())