← Home
```go
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

const LOG = 17

type LCA struct {
	n     int
	adj   [][]int
	depth []int
	up    [][]int
}

func NewLCA(n int) *LCA {
	adj := make([][]int, n+1)
	depth := make([]int, n+1)
	up := make([][]int, LOG)
	for i := 0; i < LOG; i++ {
		up[i] = make([]int, n+1)
	}
	return &LCA{n: n, adj: adj, depth: depth, up: up}
}

func (l *LCA) AddEdge(u, v int) {
	l.adj[u] = append(l.adj[u], v)
	l.adj[v] = append(l.adj[v], u)
}

func (l *LCA) Build(root int) {
	stack := []int{root}
	visited := make([]bool, l.n+1)
	visited[root] = true
	l.up[0][root] = root
	l.depth[root] = 0

	for len(stack) > 0 {
		u := stack[len(stack)-1]
		stack = stack[:len(stack)-1]
		for _, v := range l.adj[u] {
			if !visited[v] {
				visited[v] = true
				l.depth[v] = l.depth[u] + 1
				l.up[0][v] = u
				stack = append(stack, v)
			}
		}
	}

	for k := 1; k < LOG; k++ {
		for v := 1; v <= l.n; v++ {
			l.up[k][v] = l.up[k-1][l.up[k-1][v]]
		}
	}
}

func (l *LCA) lca(u, v int) int {
	if l.depth[u] < l.depth[v] {
		u, v = v, u
	}
	diff := l.depth[u] - l.depth[v]
	for k := 0; k < LOG; k++ {
		if diff&(1<<k) != 0 {
			u = l.up[k][u]
		}
	}
	if u == v {
		return u
	}
	for k := LOG - 1; k >= 0; k-- {
		if l.up[k][u] != l.up[k][v] {
			u = l.up[k][u]
			v = l.up[k][v]
		}
	}
	return l.up[0][u]
}

func (l *LCA) dist(u, v int) int {
	w := l.lca(u, v)
	return l.depth[u] + l.depth[v] - 2*l.depth[w]
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)

	scanner.Scan()
	n, _ := strconv.Atoi(scanner.Text())
	scanner.Scan()
	q, _ := strconv.Atoi(scanner.Text())

	lca := NewLCA(n)

	for i := 2; i <= n; i++ {
		scanner.Scan()
		p, _ := strconv.Atoi(scanner.Text())
		lca.AddEdge(i, p)
	}

	lca.Build(1)

	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()

	for i := 0; i < q; i++ {
		scanner.Scan()
		a, _ := strconv.Atoi(scanner.Text())
		scanner.Scan()
		b, _ := strconv.Atoi(scanner.Text())
		scanner.Scan()
		c, _ := strconv.Atoi(scanner.Text())

		d_ab := lca.dist(a, b)
		d_bc := lca.dist(b, c)
		d_ac := lca.dist(a, c)

		res1 := (d_ab + d_bc - d_ac) / 2 + 1
		res2 := (d_ac + d_bc - d_ab) / 2 + 1
		res3 := (d_ab + d_ac - d_bc) / 2 + 1

		ans := res1
		if res2 > ans {
			ans = res2
		}
		if res3 > ans {
			ans = res3
		}

		fmt.Fprintln(out, ans)
	}
}
```