- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 75 lines of Go from the credited upstream file 1009F.go.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
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 CF1009F(_r io.Reader, _w io.Writer) {11 in := bufio.NewReader(_r)12 out := bufio.NewWriter(_w)13 defer out.Flush()14 15 var n, v, w int16 Fscan(in, &n)17 g := make([][]int, n)18 for i := 1; i < n; i++ {19 Fscan(in, &v, &w)20 v--21 w--22 g[v] = append(g[v], w)23 g[w] = append(g[w], v)24 }25 26 hson := make([]int, n)27 var _f func(v, fa int) int28 _f = func(v, fa int) int {29 maxDep, hs := 0, -130 for _, w := range g[v] {31 if w != fa {32 if mxD := _f(w, v); mxD > maxDep {33 maxDep, hs = mxD, w34 }35 }36 }37 hson[v] = hs38 return maxDep + 139 }40 _f(0, -1)41 42 ans := make([]int, n)43 var f func(v, fa int) ([]int, int)44 f = func(v, fa int) (cnt []int, maxI int) {45 if hson[v] == -1 {46 return []int{1}, 047 }48 cnt, maxI = f(hson[v], v)49 for _, w := range g[v] {50 if w != fa && w != hson[v] {51 subCnt, _ := f(w, v)52 shift := len(cnt) - len(subCnt)53 for i, c := range subCnt {54 i += shift55 if cnt[i] += c; cnt[i] >= cnt[maxI] {56 maxI = i57 }58 }59 }60 }61 cnt = append(cnt, 1)62 if cnt[maxI] == 1 {63 maxI++64 }65 ans[v] = len(cnt) - 1 - maxI66 return67 }68 f(0, -1)69 for _, v := range ans {70 Fprintln(out, v)71 }72}73 7475