A and B and Lecture Rooms (Codeforces 519E)
Tags: DP, trees

A and B are preparing themselves for programming contests.The University where A and B study is a set of rooms connected by corridors. Overall, the University has n rooms connected by n - 1 corridors so that you can get from any room to any other one by moving along the corridors. The rooms are numbered from 1 to n.Every day А and B write contests in some rooms of their university, and after each contest they gather together in the same room and discuss problems. A and B want the distance from the rooms where problems are discussed to the rooms where contests are written to be equal. The distance between two rooms is the number of edges on the shortest path between them.As they write contests in new rooms every day, they asked you to help them find the number of possible rooms to discuss problems for each of the following m days.

Input: The first line contains integer n (1 ≤ n ≤ 105) — the number of rooms in the University.The next n - 1 lines describe the corridors. The i-th of these lines (1 ≤ i ≤ n - 1) contains two integers ai and bi (1 ≤ ai, bi ≤ n), showing that the i-th corridor connects rooms ai and bi.The next line contains integer m (1 ≤ m ≤ 105) — the number of queries.Next m lines describe the queries. The j-th of these lines (1 ≤ j ≤ m) contains two integers xj and yj (1 ≤ xj, yj ≤ n) that means that on the j-th day A will write the contest in the room xj, B will write in the room yj.

Output: In the i-th (1 ≤ i ≤ m) line print the number of rooms that are equidistant from the rooms where A and B write contest on the i-th day.

Note: in the first sample there is only one room at the same distance from rooms number 2 and 3 — room number 1.

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

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

Sample Outputs:
1

0
2

Solution (Python):
class LCA:

    def __init__(self, g, root, f=max, ide_ele=0):
        self.n = len(g)
        self.root = root
        self.f = f
        self.ide_ele = ide_ele
        self.num = self.n.bit_length()
        self.depth = [0] * self.n
        self.parent = [[-1] * self.n for i in range(self.num)]
        self.size = [1] * n
        s = [root]
        order = []
        while s:
            v = s.pop()
            order.append(v)
            for u in g[v]:
                if u == self.parent[0][v]:
                    continue
                self.parent[0][u] = v
                self.depth[u] = self.depth[v] + 1
                s.append(u)
        order.reverse()
        for v in order:
            p = self.parent[0][v]
            if p != -1:
                self.size[p] += self.size[v]
        for k in range(self.num - 1):
            for v in range(self.n):
                if self.parent[k][v] == -1:
                    self.parent[k + 1][v] = -1
                else:
                    self.parent[k + 1][v] = self.parent[k][self.parent[k][v]]

    def getLCA(self, u, v):
        if self.depth[u] > self.depth[v]:
            (u, v) = (v, u)
        for k in range(self.num):
            if self.depth[v] - self.depth[u] >> k & 1:
                v = self.parent[k][v]
        if u == v:
            return u
        for k in reversed(range(self.num)):
            if self.parent[k][u] != self.parent[k][v]:
                u = self.parent[k][u]
                v = self.parent[k][v]
        return self.parent[0][u]

    def search(self, v, x):
        for k in reversed(range(self.num)):
            if x >> k & 1:
                v = self.parent[k][v]
        return v
import sys
import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
n = int(input())
edge = [[] for i in range(n)]
for i in range(n - 1):
    (u, v) = map(int, input().split())
    (u, v) = (u - 1, v - 1)
    edge[u].append(v)
    edge[v].append(u)
lca = LCA(edge, 0)

def dist(u, v):
    l = lca.getLCA(u, v)
    return lca.depth[u] + lca.depth[v] - 2 * lca.depth[l]
m = int(input())
for j in range(m):
    (x, y) = map(int, input().split())
    (x, y) = (x - 1, y - 1)
    if x == y:
        print(n)
        continue
    d = dist(x, y)
    if d % 2 != 0:
        print(0)
        continue
    if lca.depth[x] < lca.depth[y]:
        (x, y) = (y, x)
    l = lca.getLCA(x, y)
    d //= 2
    u = lca.search(x, d)
    v = lca.search(x, d - 1)
    if d == lca.depth[x] - lca.depth[l]:
        w = lca.search(y, d - 1)
        print(n - lca.size[v] - lca.size[w])
    else:
        print(lca.size[u] - lca.size[v])

Solution (Python):
from io import BytesIO, IOBase
import sys
import os
import bisect
import math
import random
from collections import Counter, defaultdict, deque
from copy import deepcopy
from functools import cmp_to_key, lru_cache, reduce
from heapq import heapify, heappop, heappush, heappushpop, nlargest, nsmallest
from itertools import accumulate, combinations, permutations, count
from operator import add, iand, ior, itemgetter, mul, xor
from string import ascii_lowercase, ascii_uppercase
from typing import *

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')
BUFSIZE = 4096

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 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))

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

def I():
    return input()

def II():
    return int(input())

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

def LI():
    return list(input().split())

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

def GMI():
    return map(lambda x: int(x) - 1, input().split())

def LGMI():
    return list(map(lambda x: int(x) - 1, input().split()))
inf = float('inf')

class LCA:

    def __init__(self, path):
        n = len(path)
        stack = [n - 1]
        nthFathers = [[-1] for _ in range(n)]
        depth = [0] * n
        self.size = [1] * n
        tmp = []
        while stack:
            pt = stack.pop()
            for new_pt in path[pt]:
                if nthFathers[pt][0] != new_pt and nthFathers[new_pt][0] == -1:
                    nthFathers[new_pt][0] = pt
                    stack.append(new_pt)
                    tmp.append(new_pt)
                    depth[new_pt] = depth[pt] + 1
        tmp.reverse()
        for x in tmp:
            self.size[nthFathers[x][0]] += self.size[x]
        tmp_still_cal = list(range(n))
        while len(tmp_still_cal):
            tmp = []
            note = []
            for i in list(tmp_still_cal):
                if nthFathers[i][-1] != -1:
                    note.append(nthFathers[nthFathers[i][-1]][-1])
                    tmp.append(i)
            for (i, f) in zip(tmp, note):
                nthFathers[i].append(f)
            tmp_still_cal = tmp
        (self.nthFathers, self.depth) = (nthFathers, depth)

    def getNthFather(self, node, n):
        for i in range(len(self.nthFathers[node]) - 1, -1, -1):
            if n & 1 << i:
                node = self.nthFathers[node][i]
        return node

    def getLCA(self, node1, node2):
        if self.depth[node1] > self.depth[node2]:
            node1 = self.getNthFather(node1, self.depth[node1] - self.depth[node2])
        elif self.depth[node2] > self.depth[node1]:
            node2 = self.getNthFather(node2, self.depth[node2] - self.depth[node1])
        if node1 == node2:
            return node1
        for i in range(len(self.nthFathers[node1]) - 1, -1, -1):
            if len(self.nthFathers[node1]) <= i:
                continue
            if self.nthFathers[node1][i] != self.nthFathers[node2][i]:
                node1 = self.nthFathers[node1][i]
                node2 = self.nthFathers[node2][i]
        return self.nthFathers[node1][0]

    def getDepth(self, node):
        return self.depth[node]

    def parent(self, node):
        return self.nthFathers[node][0]
n = II()
path = [[] for _ in range(n)]
for _ in range(n - 1):
    (u, v) = GMI()
    path[u].append(v)
    path[v].append(u)
lca = LCA(path)
q = II()
for _ in range(q):
    (u, v) = GMI()
    if u == v:
        print(n)
        continue
    if (lca.getDepth(u) + lca.getDepth(v)) % 2:
        print(0)
        continue
    if lca.getDepth(u) > lca.getDepth(v):
        (u, v) = (v, u)
    x = lca.getLCA(u, v)
    if lca.getDepth(u) == lca.getDepth(v):
        k = lca.getDepth(u) - lca.getDepth(x) - 1
        pu = lca.getNthFather(u, k)
        pv = lca.getNthFather(v, k)
        print(n - lca.size[pu] - lca.size[pv])
    else:
        k = (lca.getDepth(u) + lca.getDepth(v) - lca.getDepth(x) * 2) // 2 - 1
        pv = lca.getNthFather(v, k)
        print(lca.size[lca.parent(pv)] - lca.size[pv])

Solution (Python):
from collections import defaultdict as df
from collections import deque
import os
import sys
from io import BytesIO, IOBase
_str = str
str = lambda x=b'': x if type(x) is bytes else _str(x).encode()
BUFSIZE = 8192
from types import GeneratorType

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

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')
import math
timer = [0]

@bootstrap
def dfs(v, p):
    tin[v] = timer[0]
    timer[0] += 1
    up[v][0] = p
    for i in range(1, L):
        up[v][i] = up[up[v][i - 1]][i - 1]
    for child in tree[v]:
        if child != p:
            depth[child] = depth[v] + 1
            yield dfs(child, v)
            sz[v] += sz[child]
    sz[v] += 1
    tout[v] = timer[0]
    timer[0] += 1
    yield 0

def is_ancestor(u, v):
    return tin[u] <= tin[v] and tout[u] >= tout[v]

def lca(u, v):
    if is_ancestor(u, v):
        return u
    if is_ancestor(v, u):
        return v
    for i in range(L - 1, -1, -1):
        if not is_ancestor(up[u][i], v):
            u = up[u][i]
    return up[u][0]

def cal_node(u, step):
    for i in range(L - 1, -1, -1):
        if pows[i] > step:
            continue
        u = up[u][i]
        step -= pows[i]
    return u
n = int(input())
depth = [0 for i in range(n + 1)]
L = math.ceil(math.log2(n) + 1)
pows = [2 ** i for i in range(L + 1)]
tin = [0 for i in range(n + 1)]
tout = [0 for i in range(n + 1)]
sz = [0 for i in range(n + 1)]
up = [[0 for i in range(L)] for i in range(n + 1)]
tree = df(list)
for i in range(n - 1):
    (u, v) = map(int, input().split())
    tree[u].append(v)
    tree[v].append(u)
dfs(1, 1)
m = int(input())
for _ in range(m):
    (a, b) = map(int, input().split())
    if a == b:
        print(sz[1])
    elif is_ancestor(a, b):
        dis = abs(depth[a] - depth[b])
        if dis % 2:
            print(0)
        else:
            ans_node = cal_node(b, dis // 2 - 1)
            ans_sz = sz[ans_node]
            pa_sz = sz[up[ans_node][0]]
            print(pa_sz - ans_sz)
    elif is_ancestor(b, a):
        dis = abs(depth[b] - depth[a])
        if dis % 2:
            print(0)
        else:
            ans_node = cal_node(a, dis // 2 - 1)
            ans_sz = sz[ans_node]
            pa_sz = sz[up[ans_node][0]]
            print(pa_sz - ans_sz)
    else:
        llca = lca(a, b)
        dis1 = abs(depth[llca] - depth[a])
        dis2 = abs(depth[llca] - depth[b])
        if (dis1 + dis2) % 2:
            print(0)
        elif dis1 == dis2:
            n1 = cal_node(a, dis1 - 1)
            n2 = cal_node(b, dis2 - 1)
            print(sz[1] - sz[n1] - sz[n2])
        elif dis1 > dis2:
            step_from_lca = (dis1 - dis2) // 2
            step_to_lca = dis1 - step_from_lca
            node = cal_node(a, step_to_lca - 1)
            pa_sz = sz[up[node][0]]
            print(pa_sz - sz[node])
        else:
            step_from_lca = (dis2 - dis1) // 2
            step_to_lca = dis2 - step_from_lca
            node = cal_node(b, step_to_lca - 1)
            pa_sz = sz[up[node][0]]
            print(pa_sz - sz[node])