- 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
- 68 lines of Go from the credited upstream file 1453E.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 CF1453E(_r io.Reader, _w io.Writer) {11 in := bufio.NewReader(_r)12 out := bufio.NewWriter(_w)13 defer out.Flush()14 max := func(a, b int) int {15 if a > b {16 return a17 }18 return b19 }20 21 var T, n, v, w int22 for Fscan(in, &T); T > 0; T-- {23 Fscan(in, &n)24 g := make([][]int, n)25 for i := 1; i < n; i++ {26 Fscan(in, &v, &w)27 v--28 w--29 g[v] = append(g[v], w)30 g[w] = append(g[w], v)31 }32 ans := 033 var f func(v, fa int) int34 f = func(v, fa int) int {35 mi, mx := -1, 036 for _, w := range g[v] {37 if w != fa {38 k := f(w, v)39 if mi < 0 || k < mi {40 mi = k41 }42 mx = max(mx, k)43 }44 }45 if len(g[v]) > 2 {46 ans = max(ans, mx+2) 47 }48 return mi + 1 49 }50 mx, mx2 := 0, 051 for _, w := range g[0] {52 k := f(w, 0)53 if k > mx {54 mx, mx2 = k, mx55 } else if k > mx2 {56 mx2 = k57 }58 }59 ans = max(ans, mx+1) 60 if len(g[0]) > 1 {61 ans = max(ans, mx2+2) 62 }63 Fprintln(out, ans)64 }65}66 6768