- 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
- 88 lines of Go from the credited upstream file 191C.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 CF191C(_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, q int16 Fscan(in, &n)17 type edge struct{ to, id int }18 g := make([][]edge, n)19 for i := 0; i < n-1; i++ {20 Fscan(in, &v, &w)21 v--22 w--23 g[v] = append(g[v], edge{w, i})24 g[w] = append(g[w], edge{v, i})25 }26 pa := make([]int, n)27 for i := range pa {28 pa[i] = i29 }30 var find func(int) int31 find = func(x int) int {32 if pa[x] != x {33 pa[x] = find(pa[x])34 }35 return pa[x]36 }37 38 d := make([]int, n)39 qs := make([][]int, n)40 vis := make([]int8, n)41 var _f func(int)42 _f = func(v int) {43 vis[v] = 144 for _, e := range g[v] {45 if w := e.to; vis[w] == 0 {46 _f(w)47 pa[w] = v48 }49 }50 for _, w := range qs[v] {51 if vis[w] == 2 {52 d[v]++53 d[w]++54 d[find(w)] -= 255 }56 }57 vis[v] = 258 }59 for Fscan(in, &q); q > 0; q-- {60 Fscan(in, &v, &w)61 if v != w {62 v--63 w--64 qs[v] = append(qs[v], w)65 qs[w] = append(qs[w], v)66 }67 }68 _f(0)69 70 ans := make([]interface{}, n-1)71 var f func(v, fa int) int72 f = func(v, fa int) int {73 sum := d[v]74 for _, e := range g[v] {75 if w := e.to; w != fa {76 s := f(w, v)77 ans[e.id] = s78 sum += s79 }80 }81 return sum82 }83 f(0, -1)84 Fprint(out, ans...)85}86 8788