- 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
- 64 lines of Go from the credited upstream file 219D.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 "sort"8)9 1011func CF219D(_r io.Reader, _w io.Writer) {12 in := bufio.NewReader(_r)13 out := bufio.NewWriter(_w)14 defer out.Flush()15 16 var n, v, w, rev1 int17 Fscan(in, &n)18 type edge struct{ to, dir int }19 g := make([][]edge, n+1)20 for i := 1; i < n; i++ {21 Fscan(in, &v, &w)22 g[v] = append(g[v], edge{w, 1})23 g[w] = append(g[w], edge{v, -1})24 }25 26 var f func(int, int)27 f = func(v, fa int) {28 for _, e := range g[v] {29 if e.to != fa {30 if e.dir < 0 {31 rev1++32 }33 f(e.to, v)34 }35 }36 }37 f(1, 0)38 39 mn, ans := rev1, []int{}40 var reroot func(int, int, int)41 reroot = func(v, fa, rev int) {42 if rev < mn {43 mn = rev44 ans = []int{v}45 } else if rev == mn {46 ans = append(ans, v)47 }48 for _, e := range g[v] {49 if e.to != fa {50 reroot(e.to, v, rev+e.dir)51 }52 }53 }54 reroot(1, 0, rev1)55 56 Fprintln(out, mn)57 sort.Ints(ans)58 for _, v := range ans {59 Fprint(out, v, " ")60 }61}62 6364