Fools and Roads (Codeforces 191C)
Tags: Others, trees

They say that Berland has exactly two problems, fools and roads. Besides, Berland has n cities, populated by the fools and connected by the roads. All Berland roads are bidirectional. As there are many fools in Berland, between each pair of cities there is a path (or else the fools would get upset). Also, between each pair of cities there is no more than one simple path (or else the fools would get lost). But that is not the end of Berland's special features. In this country fools sometimes visit each other and thus spoil the roads. The fools aren't very smart, so they always use only the simple paths.A simple path is the path which goes through every Berland city not more than once.The Berland government knows the paths which the fools use. Help the government count for each road, how many distinct fools can go on it.Note how the fools' paths are given in the input.

Input: The first line contains a single integer n (2 ≤ n ≤ 105) — the number of cities. Each of the next n - 1 lines contains two space-separated integers ui, vi (1 ≤ ui, vi ≤ n, ui ≠ vi), that means that there is a road connecting cities ui and vi. The next line contains integer k (0 ≤ k ≤ 105) — the number of pairs of fools who visit each other. Next k lines contain two space-separated numbers. The i-th line (i > 0) contains numbers ai, bi (1 ≤ ai, bi ≤ n). That means that the fool number 2i - 1 lives in city ai and visits the fool number 2i, who lives in city bi. The given pairs describe simple paths, because between every pair of cities there is only one simple path.

Output: Print n - 1 integer. The integers should be separated by spaces. The i-th number should equal the number of fools who can go on the i-th road. The roads are numbered starting from one in the order, in which they occur in the input.

Note: In the first sample the fool number one goes on the first and third road and the fool number 3 goes on the second, first and fourth ones.In the second sample, the fools number 1, 3 and 5 go on the first road, the fool number 5 will go on the second road, on the third road goes the fool number 3, and on the fourth one goes fool number 1.

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

5
3 4
4 5
1 4
2 4
3
2 3
1 3
3 5

Sample Outputs:
2 1 1 1

3 1 1 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, x)

def bfs(s):
    q = [s]
    dist = [inf] * (n + 1)
    dist[s] = 0
    parent = [-1] * (n + 1)
    for i in q:
        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 = int(input())
(G, s0, e) = make_graph(n, n - 1)
inf = pow(10, 9) + 1
(p, dist, parent) = bfs(1)
cnt = [1] * (n + 1)
for i in p[::-1][:-1]:
    cnt[parent[i]] += cnt[i]
x = [i for i in range(n + 1)]
for i in p:
    (j, ma, di) = (i, -1, dist[i])
    for v in range(s0[i], s0[i + 1]):
        k = G[v]
        if dist[k] < di:
            continue
        if ma < cnt[k]:
            (j, ma) = (k, cnt[k])
    x[j] = x[i]
q = int(input())
dp = [0] * (n + 1)
for i in range(q):
    (a, b) = map(int, input().split())
    dp[a] += 1
    dp[b] += 1
    while x[a] ^ x[b]:
        if dist[x[a]] >= dist[x[b]]:
            a = parent[x[a]]
        else:
            b = parent[x[b]]
    c = a if dist[a] <= dist[b] else b
    dp[c] -= 2
for i in p[::-1][:-1]:
    dp[parent[i]] += dp[i]
ans = [0] * (n - 1)
for i in range(n - 1):
    (u, v) = (e[2 * i], e[2 * i + 1])
    ans0 = dp[u] if dist[u] >= dist[v] else dp[v]
    ans[i] = ans0
sys.stdout.write(' '.join(map(str, ans)))

Solution (Python):
import os
import sys
from io import BytesIO, IOBase
from types import GeneratorType
from collections import defaultdict
BUFSIZE = 8192

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, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
sys.setrecursionlimit(2 * 10 ** 5)

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
MA = 10 ** 5 + 1
level = 20
tree = [[] for i in range(MA)]
depth = [0 for i in range(MA)]
parent = [[0 for i in range(level)] for j in range(MA)]

@bootstrap
def dfs(cur, prev):
    depth[cur] = depth[prev] + 1
    parent[cur][0] = prev
    res.append(cur)
    for i in range(len(tree[cur])):
        if tree[cur][i] != prev:
            yield dfs(tree[cur][i], cur)
    res.append(-cur)
    yield

def precomputeSparseMatrix(n):
    for i in range(1, level):
        for node in range(1, n + 1):
            if parent[node][i - 1] != -1:
                parent[node][i] = parent[parent[node][i - 1]][i - 1]

def lca(u, v):
    if depth[v] < depth[u]:
        (u, v) = (v, u)
    diff = depth[v] - depth[u]
    for i in range(level):
        if diff >> i & 1:
            v = parent[v][i]
    if u == v:
        return u
    i = level - 1
    while i >= 0:
        if parent[u][i] != parent[v][i]:
            u = parent[u][i]
            v = parent[v][i]
        i += -1
    return parent[u][0]

def add(a, b):
    tree[a].append(b)
    tree[b].append(a)

def res(s, t, f):
    p = lca(t, f)
    q = lca(s, f)
    if p == q:
        r = depth[lca(s, t)] - depth[p]
        return min(depth[p] + depth[f] - 2 * depth[p] + 1 + r, depth[q] + depth[f] - 2 * depth[q] + 1 + r)
    return min(depth[p] + depth[f] - 2 * depth[p] + 1, depth[q] + depth[f] - 2 * depth[q] + 1)
ord = []
n = int(input())
for j in range(n - 1):
    (u, v) = map(int, input().split())
    ord.append([u, v])
    tree[u].append(v)
    tree[v].append(u)
res = []
dfs(1, 0)
precomputeSparseMatrix(n)
d = dict()
l = len(res)
req = [0] * l
for j in range(l):
    d[res[j]] = j
k = int(input())
c = [0] * (n + 1)
for j in range(k):
    (u, v) = map(int, input().split())
    lc = lca(u, v)
    c[lc] += 1
    if u == lc:
        indu = d[u]
        indv = d[v]
        req[indu] += 1
        req[indv + 1] += -1
    elif v == lc:
        indu = d[u]
        indv = d[v]
        req[indv] += 1
        req[indu + 1] += -1
    else:
        indl = d[lc]
        indu = d[u]
        indv = d[v]
        req[indl] += 1
        req[indu + 1] += -1
        req[indl + 1] += 1
        req[indv + 1] += -1
for j in range(1, l):
    req[j] += req[j - 1]
ans = [0] * (n + 1)
for j in range(1, n + 1):
    ans[j] = req[d[j]] - req[d[-j]]
for j in ord:
    l = lca(j[0], j[1])
    if l == j[0]:
        print(ans[j[1]] - c[j[1]], end=' ')
    else:
        print(ans[j[0]] - c[j[0]], end=' ')

Solution (Python):
import sys
MAX_H = 30
input = sys.stdin.readline
output = lambda x: sys.stdout.write(x)

class Node:

    def __init__(self):
        self.pars = []
        self.conn = {}
        self.count = 0
        self.depth = 0
n = int(input())
nodes = [Node() for _ in range(n + 1)]
for ri in range(n - 1):
    (u, v) = map(int, input().split())
    nodes[u].conn[v] = ri
    nodes[v].conn[u] = ri
pairs = []
k = int(input())
for _ in range(k):
    pairs.append(tuple(map(int, input().split())))
stack = [1]
while len(stack) > 0:
    curr = stack.pop()
    cn = nodes[curr]
    for (o, r) in cn.conn.items():
        stack.append(o)
        on = nodes[o]
        del on.conn[curr]
        on.depth = cn.depth + 1
        on.pars.append(curr)
for jh in range(1, MAX_H):
    for i in range(1, n + 1):
        cn = nodes[i]
        if len(cn.pars) >= jh:
            par = nodes[cn.pars[jh - 1]]
            if len(par.pars) >= jh:
                cn.pars.append(par.pars[jh - 1])

def lca(a, b):
    if nodes[a].depth > nodes[b].depth:
        (a, b) = (b, a)
    dd = nodes[b].depth - nodes[a].depth
    for h in range(MAX_H):
        if dd & 1 << h:
            b = nodes[b].pars[h]
    if a == b:
        return a
    for h in range(MAX_H)[::-1]:
        if h < len(nodes[a].pars):
            pa = nodes[a].pars[h]
            pb = nodes[b].pars[h]
            if pa != pb:
                a = pa
                b = pb
    return nodes[a].pars[0]
for (a, b) in pairs:
    nodes[a].count += 1
    nodes[b].count += 1
    nodes[lca(a, b)].count -= 2
roads = [0 for _ in range(n - 1)]
stack = [(1, 0)]
while len(stack) > 0:
    (curr, state) = stack.pop()
    cn = nodes[curr]
    if state == 0:
        stack.append((curr, 1))
        for o in cn.conn:
            stack.append((o, 0))
    else:
        for (o, r) in cn.conn.items():
            oc = nodes[o].count
            cn.count += oc
            roads[r] = oc
output(' '.join(map(str, roads)))
output('\n')