Demiurges Play Again (Codeforces 538E)
Tags: Math, trees

Demiurges Shambambukli and Mazukta love to watch the games of ordinary people. Today, they noticed two men who play the following game.There is a rooted tree on n nodes, m of which are leaves (a leaf is a nodes that does not have any children), edges of the tree are directed from parent to children. In the leaves of the tree integers from 1 to m are placed in such a way that each number appears exactly in one leaf.Initially, the root of the tree contains a piece. Two players move this piece in turns, during a move a player moves the piece from its current nodes to one of its children; if the player can not make a move, the game ends immediately. The result of the game is the number placed in the leaf where a piece has completed its movement. The player who makes the first move tries to maximize the result of the game and the second player, on the contrary, tries to minimize the result. We can assume that both players move optimally well.Demiurges are omnipotent, so before the game they can arbitrarily rearrange the numbers placed in the leaves. Shambambukli wants to rearrange numbers so that the result of the game when both players play optimally well is as large as possible, and Mazukta wants the result to be as small as possible. What will be the outcome of the game, if the numbers are rearranged by Shambambukli, and what will it be if the numbers are rearranged by Mazukta? Of course, the Demiurges choose the best possible option of arranging numbers.

Input: The first line contains a single integer n — the number of nodes in the tree (1 ≤ n ≤ 2·105).Each of the next n - 1 lines contains two integers ui and vi (1 ≤ ui, vi ≤ n) — the ends of the edge of the tree; the edge leads from node ui to node vi. It is guaranteed that the described graph is a rooted tree, and the root is the node 1.

Output: Print two space-separated integers — the maximum possible and the minimum possible result of the game.

Note: Consider the first sample. The tree contains three leaves: 3, 4 and 5. If we put the maximum number 3 at node 3, then the first player moves there and the result will be 3. On the other hand, it is easy to see that for any rearrangement the first player can guarantee the result of at least 2.In the second sample no matter what the arragment is the first player can go along the path that ends with a leaf with number 3.

Sample Inputs:
5
1 2
1 3
2 4
2 5

6
1 2
1 3
3 4
1 5
5 6

Sample Outputs:
3 2

3 3

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

def solve():
    n = int(input())
    g = [[] for i in range(n + 1)]
    for i in range(1, n):
        (u, v) = map(int, input().split())
        g[u].append(v)
        g[v].append(u)
    q = [1]
    d = [None] * (n + 1)
    d[1] = 0
    i = 0
    while i < len(q):
        x = q[i]
        i += 1
        for v in g[x]:
            if d[v] is None:
                q.append(v)
                d[v] = d[x] + 1
                g[v].remove(x)
    m = [0] * (n + 1)
    M = [0] * (n + 1)
    cnt = 0
    for i in range(len(q) - 1, -1, -1):
        x = q[i]
        if len(g[x]) == 0:
            m[x] = 1
            M[x] = 1
            cnt += 1
        elif d[x] % 2 == 0:
            c = 0
            C = int(1000000000.0)
            for v in g[x]:
                c += m[v]
            for v in g[x]:
                C = min(C, M[v])
            m[x] = c
            M[x] = C
        else:
            c = int(1000000000.0)
            C = 0
            for v in g[x]:
                c = min(c, m[v])
            for v in g[x]:
                C += M[v]
            m[x] = c
            M[x] = C
    print(cnt + 1 - M[x], m[1])
solve()

Solution (Python):
from collections import deque
from operator import not_

def ranks(n, T):
    L = [None for _ in range(n)]
    L[0] = 0
    R = [[0]]
    Q = deque()
    Q.append(0)
    while Q:
        p = Q.popleft()
        if not T[p]:
            continue
        l = L[p] + 1
        for c in T[p]:
            L[c] = l
        if l == len(R):
            R.append([])
        R[l].extend(T[p])
        Q.extend(T[p])
    return R

def tree(n, E):
    T = [[] for _ in range(n)]
    for (p, c) in E:
        T[p - 1].append(c - 1)
    R = ranks(n, T)
    M = [None for _ in range(n)]
    S = [None for _ in range(n)]
    for l in reversed(range(len(R))):
        for p in R[l]:
            if T[p]:
                if l % 2:
                    M[p] = min((M[c] for c in T[p]))
                    S[p] = sum((S[c] for c in T[p]))
                else:
                    M[p] = sum((M[c] for c in T[p]))
                    S[p] = min((S[c] for c in T[p]))
            else:
                M[p] = 1
                S[p] = 1
    m = sum(map(not_, T))
    return (M[0], m + 1 - S[0])

def main():
    n = readint()
    E = readintll(n - 1)
    (m, s) = tree(n, E)
    print(f'{s} {m}')
import sys
import time
import traceback
from contextlib import contextmanager
from io import StringIO

def readint():
    return int(input())

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

def readintl():
    return list(readinti())

def readintll(k):
    return [readintl() for _ in range(k)]

def log(*args, **kwargs):
    print(*args, **kwargs, file=sys.stderr)

@contextmanager
def patchio(i):
    try:
        sys.stdin = StringIO(i)
        sys.stdout = StringIO()
        yield sys.stdout
    finally:
        sys.stdin = sys.__stdin__
        sys.stdout = sys.__stdout__

def do_test(k, test):
    try:
        log(f'TEST {k}')
        (i, o) = test
        with patchio(i) as r:
            t0 = time.time()
            main()
            t1 = time.time()
        if r.getvalue() == o:
            log(f'OK ({int((t1 - t0) * 1000000) / 1000:0.3f} ms)\n')
        else:
            log(f'Expected:\n{o}Got ({int((t1 - t0) * 1000000) / 1000:0.3f} ms):\n{r.getvalue()}')
    except Exception:
        traceback.print_exc()
        log()

def test(ts):
    for k in ts or range(len(tests)):
        do_test(k, tests[k])
tests = [('5\n1 2\n1 3\n2 4\n2 5\n', '3 2\n'), ('6\n1 2\n1 3\n3 4\n1 5\n5 6\n', '3 3\n')]
if __name__ == '__main__':
    from argparse import ArgumentParser
    parser = ArgumentParser()
    parser.add_argument('--test', '-t', type=int, nargs='*')
    args = parser.parse_args()
    main() if args.test is None else test(args.test)

Solution (Python):
import sys
fin = sys.stdin
n = int(fin.readline())
ut = [-1] * n
vc = [[] for i in range(0, n)]
cvc = [[] for i in range(0, n)]
nr = [0] * n
for i in range(0, n - 1):
    (a, b) = [int(number) for number in fin.readline().split()]
    a -= 1
    b -= 1
    vc[a].append(b)
    cvc[b].append(a)
    nr[a] += 1
size = [0] * n
mx = [0] * n

def nonzero(x):
    if not x:
        return 0
    return 1
stk = []
size = [0] * n
for i in range(0, n):
    if nr[i] == 0:
        stk.append(i)
        size[i] = 1
order = []
while nonzero(stk):
    x = stk.pop(-1)
    order.append(x)
    for p in cvc[x]:
        nr[p] -= 1
        if nr[p] == 0:
            stk.append(p)
h = [0] * n
for i in range(n - 1, -1, -1):
    x = order[i]
    for p in vc[x]:
        h[p] = h[x] + 1
for x in order:
    for p in vc[x]:
        size[x] += size[p]

def solv(tp, mx):
    for x in order:
        if h[x] % 2 == tp:
            r = 999999999
            for p in vc[x]:
                r = min(r, size[p] - mx[p] + 1)
            if r == 999999999:
                r = 1
            mx[x] = r
        else:
            r = 0
            for p in vc[x]:
                r += size[p] - mx[p]
            mx[x] = r + 1
solv(0, mx)
print(size[0] - mx[0] + 1, end=' ')
solv(1, mx)
print(size[0] - mx[0] + 1)