- 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
- 104 lines of Go from the credited upstream file 519E.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 "math/bits"8)9 1011func CF519E(_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, q int17 Fscan(in, &n)18 g := make([][]int, n)19 for i := 1; i < n; i++ {20 Fscan(in, &v, &w)21 v--22 w--23 g[v] = append(g[v], w)24 g[w] = append(g[w], v)25 }26 27 const mx = 1828 pa := make([][mx]int, n)29 dep := make([]int, n)30 size := make([]int, n)31 var f func(int, int) int32 f = func(v, p int) int {33 pa[v][0] = p34 sz := 135 for _, w := range g[v] {36 if w != p {37 dep[w] = dep[v] + 138 sz += f(w, v)39 }40 }41 size[v] = sz42 return sz43 }44 f(0, -1)45 for k := 0; k+1 < mx; k++ {46 for v := range pa {47 if p := pa[v][k]; p != -1 {48 pa[v][k+1] = pa[p][k]49 } else {50 pa[v][k+1] = -151 }52 }53 }54 uptoDep := func(v, d int) int {55 for k := dep[v] - d; k > 0; k &= k - 1 {56 v = pa[v][bits.TrailingZeros(uint(k))]57 }58 return v59 }60 _lca := func(v, w int) int {61 if dep[v] > dep[w] {62 v, w = w, v63 }64 w = uptoDep(w, dep[v])65 if v == w {66 return v67 }68 for k := mx - 1; k >= 0; k-- {69 if pa[v][k] != pa[w][k] {70 v, w = pa[v][k], pa[w][k]71 }72 }73 return pa[v][0]74 }75 76 for Fscan(in, &q); q > 0; q-- {77 Fscan(in, &v, &w)78 if v == w {79 Fprintln(out, n)80 continue81 }82 v--83 w--84 if dep[v] > dep[w] {85 v, w = w, v86 }87 lca := _lca(v, w)88 d := dep[v] + dep[w] - dep[lca]<<189 if d&1 == 1 {90 Fprintln(out, 0)91 continue92 }93 uw := uptoDep(w, dep[w]-d>>1+1)94 if p := pa[uw][0]; p != lca {95 Fprintln(out, size[p]-size[uw])96 } else {97 uv := uptoDep(v, dep[v]-d>>1+1)98 Fprintln(out, n-size[uv]-size[uw])99 }100 }101}102 103104