Journey (Codeforces 839C)
Tags: DP, probabilities

There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads.Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link https://en.wikipedia.org/wiki/Expected_value.

Input: The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities.Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road.It is guaranteed that one can reach any city from any other by the roads.

Output: Print a number — the expected length of their journey. The journey starts in the city 1.Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6.Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .

Note: In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5.In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.

Sample Inputs:
4
1 2
1 3
2 4

5
1 2
1 3
3 4
2 5

Sample Outputs:
1.500000000000000

2.000000000000000

Solution (Python):
import sys

def main():
    n = int(input())
    if n == 1:
        print(0)
        return
    x = [[] for i in range(n)]
    for i in range(n - 1):
        (a, b) = map(int, sys.stdin.readline().split())
        x[a - 1].append(b - 1)
        x[b - 1].append(a - 1)
    isl = [False] * n
    for i in range(1, n):
        if len(x[i]) == 1:
            isl[i] = True
    u = [False] * n
    u[0] = True
    q = [(0, 0, 1 / len(x[0]))]
    a = 0
    while len(q) != 0:
        (c, s, t) = q.pop()
        for i in x[c]:
            if not u[i]:
                if isl[i]:
                    a += (s + 1) * t
                else:
                    q.append((i, s + 1, t / (len(x[i]) - 1)))
                u[i] = True
    print(a)
main()

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

def solve(n, graph):
    stack = [(0, 0, 1.0)]
    visited = {0}
    ans = 0
    while stack:
        (node, l, prob) = stack.pop()
        numNodes = 0
        tmp = []
        leaf = True
        for nei in graph[node]:
            if nei not in visited:
                visited.add(nei)
                numNodes += 1
                tmp.append(nei)
                leaf = False
        for q in tmp:
            stack.append((q, l + 1, prob / numNodes))
        if leaf:
            ans += prob * l
    print(ans)
n = int(input())
graph = [[] for _ in range(n)]
for _ in range(n - 1):
    (u, v) = map(int, input().split())
    graph[u - 1].append(v - 1)
    graph[v - 1].append(u - 1)
solve(n, graph)

Solution (Python):
from sys import stdin, stdout, setrecursionlimit
setrecursionlimit(10 ** 7)
import threading
threading.stack_size(2 ** 26)

class SOLVE:

    def dfs(self, child, parent, node):
        total = 0
        for v in node[child]:
            if v != parent:
                total += self.dfs(v, child, node) + 1
        return total / (len(node[child]) - (1 if parent else 0)) if total else 0

    def solve(self):
        R = stdin.readline
        W = stdout.write
        n = int(R())
        node = [[] for i in range(n + 1)]
        for _ in range(n - 1):
            (u, v) = [int(x) for x in R().split()]
            node[u].append(v)
            node[v].append(u)
        print(self.dfs(1, 0, node))
        return 0

def main():
    s = SOLVE()
    s.solve()
threading.Thread(target=main).start()