Misha, Grisha and Underground (Codeforces 832D)
Tags: Others, trees

Misha and Grisha are funny boys, so they like to use new underground. The underground has n stations connected with n - 1 routes so that each route connects two stations, and it is possible to reach every station from any other.The boys decided to have fun and came up with a plan. Namely, in some day in the morning Misha will ride the underground from station s to station f by the shortest path, and will draw with aerosol an ugly text "Misha was here" on every station he will pass through (including s and f). After that on the same day at evening Grisha will ride from station t to station f by the shortest path and will count stations with Misha's text. After that at night the underground workers will wash the texts out, because the underground should be clean. The boys have already chosen three stations a, b and c for each of several following days, one of them should be station s on that day, another should be station f, and the remaining should be station t. They became interested how they should choose these stations s, f, t so that the number Grisha will count is as large as possible. They asked you for help.

Input: The first line contains two integers n and q (2 ≤ n ≤ 105, 1 ≤ q ≤ 105) — the number of stations and the number of days.The second line contains n - 1 integers p2, p3, ..., pn (1 ≤ pi ≤ n). The integer pi means that there is a route between stations pi and i. It is guaranteed that it's possible to reach every station from any other.The next q lines contains three integers a, b and c each (1 ≤ a, b, c ≤ n) — the ids of stations chosen by boys for some day. Note that some of these ids could be same.

Output: Print q lines. In the i-th of these lines print the maximum possible number Grisha can get counting when the stations s, t and f are chosen optimally from the three stations on the i-th day.

Note: In the first example on the first day if s = 1, f = 2, t = 3, Misha would go on the route 1  2, and Grisha would go on the route 3  1  2. He would see the text at the stations 1 and 2. On the second day, if s = 3, f = 2, t = 3, both boys would go on the route 3  1  2. Grisha would see the text at 3 stations.In the second examle if s = 1, f = 3, t = 2, Misha would go on the route 1  2  3, and Grisha would go on the route 2  3 and would see the text at both stations.

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

4 1
1 2 3
1 2 3

Sample Outputs:
2
3

2

Solution (Python):
import os, sys
from io import BytesIO, IOBase

def euler_path(n, path):
    height = [0] * n + [10 ** 10]
    (euler, st, visi, he) = ([], [0], [1] + [0] * (n - 1), 0)
    first = [-1] * n
    while len(st):
        x = st[-1]
        euler.append(x)
        if first[x] == -1:
            first[x] = len(euler) - 1
        while len(path[x]) and visi[path[x][-1]]:
            path[x].pop()
        if not len(path[x]):
            he -= 1
            st.pop()
        else:
            i = path[x].pop()
            he += 1
            st.append(i)
            (height[i], visi[i]) = (he, 1)
    return (height, euler, first)

def cons(euler, height):
    n = len(euler)
    xx = n.bit_length()
    dp = [[n] * n for _ in range(xx)]
    dp[0] = euler
    for i in range(1, xx):
        for j in range(n - (1 << i) + 1):
            (a, b) = (dp[i - 1][j], dp[i - 1][j + (1 << i - 1)])
            dp[i][j] = a if height[a] < height[b] else b
    return dp

def lca(l, r, dp, height, first):
    (l, r) = (first[l], first[r])
    if l > r:
        (l, r) = (r, l)
    xx1 = (r - l + 1).bit_length() - 1
    (a, b) = (dp[xx1][l], dp[xx1][r - (1 << xx1) + 1])
    return a if height[a] < height[b] else b

def solve(s, f, t, dp, height, first):
    a = lca(s, f, dp, height, first)
    b = lca(t, f, dp, height, first)
    ans = height[f] - max(height[a], height[b]) + 1
    if a == b:
        x = lca(s, t, dp, height, first)
        ans += height[x] - height[a]
    return ans

def main():
    (n, q) = map(int, input().split())
    path = [[] for _ in range(n)]
    for (ind, i) in enumerate(map(int, input().split())):
        path[ind + 1].append(i - 1)
        path[i - 1].append(ind + 1)
    (height, euler, first) = euler_path(n, path)
    dp = cons(euler, height)
    for _ in range(q):
        (a, b, c) = map(lambda xx: int(xx) - 1, input().split())
        print(max(solve(a, b, c, dp, height, first), solve(a, c, b, dp, height, first), solve(b, a, c, dp, height, first)))
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')
if __name__ == '__main__':
    main()

Solution (Python):
import os, sys
from io import BytesIO, IOBase

def pre(n, path, lim):
    up = [[-1] * (lim + 1) for _ in range(n)]
    (st, visi, height) = ([0], [1] + [0] * (n - 1), [0] * n)
    (start, finish, time) = ([0] * n, [0] * n, 0)
    while len(st):
        x = st[-1]
        (y, j) = (up[x][0], 0)
        while y != -1:
            up[x][j] = y
            y = up[y][j]
            j += 1
        while len(path[x]) and visi[path[x][-1]]:
            path[x].pop()
        if not len(path[x]):
            time += 1
            finish[x] = time
            st.pop()
        else:
            i = path[x].pop()
            st.append(i)
            time += 1
            (visi[i], start[i], up[i][0], height[i]) = (1, time, x, height[x] + 1)
    return (start, finish, up, height)

def is_ancestor(u, v, start, finish):
    return start[u] <= start[v] and finish[u] >= finish[v]

def lca(u, v, up, start, finish, lim):
    if is_ancestor(u, v, start, finish):
        return u
    if is_ancestor(v, u, start, finish):
        return v
    for i in range(lim, -1, -1):
        if up[u][i] != -1 and (not is_ancestor(up[u][i], v, start, finish)):
            u = up[u][i]
    return up[u][0]

def solve(s, f, t, up, start, finish, lim, height):
    a = lca(s, f, up, start, finish, lim)
    b = lca(t, f, up, start, finish, lim)
    ans = height[f] - max(height[a], height[b]) + 1
    if a == b:
        x = lca(s, t, up, start, finish, lim)
        ans += height[x] - height[a]
    return ans

def main():
    (n, q) = map(int, input().split())
    path = [[] for _ in range(n)]
    for (ind, i) in enumerate(map(int, input().split())):
        path[ind + 1].append(i - 1)
        path[i - 1].append(ind + 1)
    lim = n.bit_length()
    (start, finish, up, height) = pre(n, path, lim)
    for _ in range(q):
        (a, b, c) = map(lambda xx: int(xx) - 1, input().split())
        print(max(solve(a, b, c, up, start, finish, lim, height), solve(a, c, b, up, start, finish, lim, height), solve(b, a, c, up, start, finish, lim, height)))
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')
if __name__ == '__main__':
    main()

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(3 * 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
    for i in range(len(tree[cur])):
        if tree[cur][i] != prev:
            yield dfs(tree[cur][i], 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)
(n, q) = map(int, input().split())
p = list(map(int, input().split()))
for j in range(n - 1):
    tree[p[j]].append(j + 2)
    tree[j + 2].append(p[j])
dfs(1, 0)
precomputeSparseMatrix(n)
for j in range(q):
    (a, b, c) = map(int, input().split())
    print(max(res(a, b, c), res(a, c, b), res(b, c, a)))