Approach
Depth-first search
For Codeforces 1632E2 — Distance Tree (hard version), 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
- 68 lines of Go from the credited upstream file 1632E2.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)8 910func cf1632E2(in io.Reader, _w io.Writer) {11 out := bufio.NewWriter(_w)12 defer out.Flush()13 var T, n int14 for Fscan(in, &T); T > 0; T-- {15 Fscan(in, &n)16 g := make([][]int, n+1)17 for i := 1; i < n; i++ {18 var v, w int19 Fscan(in, &v, &w)20 g[v] = append(g[v], w)21 g[w] = append(g[w], v)22 }23 24 dep := make([]int, n+1)25 dep[0] = -126 mx := make([]int, n+1)27 f := make([]int, n+2)28 var dfs func(int, int)29 dfs = func(v, fa int) {30 mx[v] = dep[fa] + 131 dep[v] = dep[fa] + 132 m := mx[v]33 for _, w := range g[v] {34 if w == fa {35 continue36 }37 dfs(w, v)38 if mx[v] < mx[w] {39 m = mx[v]40 mx[v] = mx[w]41 } else {42 m = max(m, mx[w])43 }44 }45 if m > 0 {46 f[m-1] = max(f[m-1], mx[v]+m-dep[v]*2)47 }48 }49 dfs(1, 0)50 d1 := mx[1]51 52 for i := n; i > 0; i-- {53 f[i] = max(f[i], f[i+1])54 }55 56 j := 057 for i := 1; i <= n; i++ {58 for j < d1 && (f[j]+1)/2+i > j {59 j++60 }61 Fprint(out, j, " ")62 }63 Fprintln(out)64 }65}66 6768