Approach
Depth-first search
For Codeforces 832D — Misha, Grisha and Underground, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 110 lines of Go from the credited upstream file 832D.go.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1package main2 3import (4 "bufio"5 . "fmt"6 "io"7 "math/bits"8)9 1011func Sol832D(reader io.Reader, writer io.Writer) {12 in := bufio.NewScanner(reader)13 in.Split(bufio.ScanWords)14 out := bufio.NewWriter(writer)15 defer out.Flush()16 read := func() (x int) {17 in.Scan()18 for _, b := range in.Bytes() {19 x = x*10 + int(b-'0')20 }21 return22 }23 maxs := func(vals ...int) int {24 ans := vals[0]25 for _, val := range vals[1:] {26 if val > ans {27 ans = val28 }29 }30 return ans31 }32 33 n, q := read(), read()34 g := make([][]int, n)35 for v := 1; v < n; v++ {36 w := read() - 137 g[v] = append(g[v], w)38 g[w] = append(g[w], v)39 }40 41 vs := make([]int, 0, 2*n-1)42 pos := make([]int, n)43 depths := make([]int, 0, 2*n-1)44 dis := make([]int, n)45 var dfs func(v, fa, d int)46 dfs = func(v, fa, d int) {47 pos[v] = len(vs)48 vs = append(vs, v)49 depths = append(depths, d)50 dis[v] = d51 for _, w := range g[v] {52 if w != fa {53 dfs(w, v, d+1)54 vs = append(vs, v)55 depths = append(depths, d)56 }57 }58 }59 dfs(0, -1, 0)60 61 type pair struct{ v, i int }62 var st [][18]pair63 stInit := func(a []int) {64 n := len(a)65 st = make([][18]pair, n)66 for i := range st {67 st[i][0] = pair{a[i], i}68 }69 for j := uint(1); 1<<j <= n; j++ {70 for i := 0; i+(1<<j)-1 < n; i++ {71 st0, st1 := st[i][j-1], st[i+(1<<(j-1))][j-1]72 if st0.v < st1.v {73 st[i][j] = st074 } else {75 st[i][j] = st176 }77 }78 }79 }80 stQuery := func(l, r int) int {81 k := uint(bits.Len(uint(r-l+1)) - 1)82 st0, st1 := st[l][k], st[r-(1<<k)+1][k]83 if st0.v < st1.v {84 return st0.i85 }86 return st1.i87 }88 lca := func(v, w int) int {89 pv, pw := pos[v], pos[w]90 if pv > pw {91 pv, pw = pw, pv92 }93 return vs[stQuery(pv, pw)]94 }95 calcDis := func(v, w int) int {96 return dis[v] + dis[w] - 2*dis[lca(v, w)]97 }98 99 stInit(depths)100 for ; q > 0; q-- {101 a, b, c := read()-1, read()-1, read()-1102 v := lca(a, b) ^ lca(a, c) ^ lca(b, c)103 Fprintln(out, 1+maxs(calcDis(v, a), calcDis(v, b), calcDis(v, c)))104 }105}106 107108109110