- 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
- 92 lines of Go from the credited upstream file 842E.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 cf842E(in io.Reader, _w io.Writer) {12 out := bufio.NewWriter(_w)13 defer out.Flush()14 var n, p int15 Fscan(in, &n)16 n++17 18 const mx = 1919 pa := make([][mx]int, n+1)20 dep := make([]int, n+1)21 uptoDep := func(v, d int) int {22 for k := uint32(dep[v] - d); k > 0; k &= k - 1 {23 v = pa[v][bits.TrailingZeros32(k)]24 }25 return v26 }27 lca := func(v, w int) int {28 if dep[v] > dep[w] {29 v, w = w, v30 }31 w = uptoDep(w, dep[v])32 if w == v {33 return v34 }35 for i := mx - 1; i >= 0; i-- {36 pv, pw := pa[v][i], pa[w][i]37 if pv != pw {38 v, w = pv, pw39 }40 }41 return pa[v][0]42 }43 dis := func(v, w int) int { return dep[v] + dep[w] - dep[lca(v, w)]*2 }44 45 a, b := []int{1}, []int{}46 dia := 047 for i := 2; i <= n; i++ {48 Fscan(in, &p)49 dep[i] = dep[p] + 150 pa[i][0] = p51 for j := range mx - 1 {52 pa[i][j+1] = pa[pa[i][j]][j]53 }54 55 da, db := 0, 056 if len(a) > 0 {57 da = dis(i, a[0])58 }59 if len(b) > 0 {60 db = dis(i, b[0])61 }62 63 if max(da, db) > dia {64 dia++65 if da >= db {66 for _, v := range b {67 if dis(i, v) == dia {68 a = append(a, v)69 }70 }71 b = []int{i}72 } else {73 for _, v := range a {74 if dis(i, v) == dia {75 b = append(b, v)76 }77 }78 a = []int{i}79 }80 } else if max(da, db) == dia {81 if da == dia {82 b = append(b, i)83 } else {84 a = append(a, i)85 }86 }87 Fprintln(out, len(a)+len(b))88 }89}90 9192