- 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
- 69 lines of Go from the credited upstream file 1406C.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 CF1406C(_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+1)25 for i := 1; i < n; i++ {26 Fscan(in, &v, &w)27 g[v] = append(g[v], w)28 g[w] = append(g[w], v)29 }30 31 ct := []int{}32 min := int(1e9)33 var f func(v, fa int) int34 f = func(v, fa int) int {35 sz, maxSz := 1, 036 for _, w := range g[v] {37 if w != fa {38 s := f(w, v)39 sz += s40 maxSz = max(maxSz, s)41 }42 }43 maxSz = max(maxSz, n-sz)44 if maxSz < min {45 min = maxSz46 ct = []int{v}47 } else if maxSz == min {48 ct = append(ct, v)49 }50 return sz51 }52 f(1, 0)53 if len(ct) == 1 {54 Fprintln(out, v, w)55 Fprintln(out, v, w)56 } else {57 v, w = ct[0], ct[1]58 u := g[v][0]59 if u == w {60 u = g[v][1]61 }62 Fprintln(out, v, u)63 Fprintln(out, w, u)64 }65 }66}67 6869