Approach
Depth-first search
For Codeforces 1827D — Two Centroids, 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
- 122 lines of Go from the credited upstream file 1827D.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 1011type fenwick27 []int12 13func (t fenwick27) add(i int) {14 for ; i < len(t); i += i & -i {15 t[i]++16 }17}18 19func (t fenwick27) pre(i int) (res int) {20 for ; i > 0; i &= i - 1 {21 res += t[i]22 }23 return24}25 26func (t fenwick27) query(l, r int) int {27 return t.pre(r) - t.pre(l-1)28}29 30func cf1827D(in io.Reader, _w io.Writer) {31 out := bufio.NewWriter(_w)32 defer out.Flush()33 var T, n, size int34 for Fscan(in, &T); T > 0; T-- {35 Fscan(in, &n)36 g := make([][]int, n)37 for w := 1; w < n; w++ {38 var v int39 Fscan(in, &v)40 g[v-1] = append(g[v-1], w)41 }42 43 pa := make([][19]int, n)44 dep := make([]int, n)45 tin := make([]int, n)46 tout := make([]int, n)47 now := 048 var dfs func(int, int)49 dfs = func(v, p int) {50 now++51 tin[v] = now52 pa[v][0] = p53 for _, w := range g[v] {54 if w != p {55 dep[w] = dep[v] + 156 dfs(w, v)57 }58 }59 tout[v] = now60 }61 dfs(0, -1)62 63 mx := bits.Len(uint(n))64 for i := range mx - 1 {65 for v := range pa {66 p := pa[v][i]67 if p != -1 {68 pa[v][i+1] = pa[p][i]69 } else {70 pa[v][i+1] = -171 }72 }73 }74 up := func(v, d int) int {75 for k := uint32(dep[v] - d); k > 0; k &= k - 1 {76 v = pa[v][bits.TrailingZeros32(k)]77 }78 return v79 }80 down := func(v, to int) int {81 if dep[to] <= dep[v] {82 return -183 }84 to = up(to, dep[v]+1)85 if pa[to][0] == v {86 return to87 }88 return -189 }90 91 t := make(fenwick27, n+1)92 t.add(tin[0])93 ct, maxSonSize := 0, 094 for i := 1; i < n; i++ {95 nodes := i + 196 t.add(tin[i])97 98 son := down(ct, i)99 if son >= 0 {100 size = t.query(tin[son], tout[son])101 } else {102 size = nodes - t.query(tin[ct], tout[ct])103 }104 maxSonSize = max(maxSonSize, size)105 106 if maxSonSize > nodes/2 {107 maxSonSize = nodes / 2108 if son >= 0 {109 ct = son110 } else {111 ct = pa[ct][0]112 }113 }114 115 Fprint(out, nodes-maxSonSize*2, " ")116 }117 Fprintln(out)118 }119}120 121122