- 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
- 73 lines of Go from the credited upstream file 379F.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 cf379F(in io.Reader, _w io.Writer) {12 out := bufio.NewWriter(_w)13 defer out.Flush()14 var q int15 Fscan(in, &q)16 17 n := 5 + q*218 const mx = 2019 pa := make([][mx]int, n)20 pa[2][0], pa[3][0], pa[4][0] = 1, 1, 121 dep := make([]int, n)22 dep[2], dep[3], dep[4] = 1, 1, 123 24 uptoDep := func(v, d int) int {25 for k := uint(dep[v] - d); k > 0; k &= k - 1 {26 v = pa[v][bits.TrailingZeros(k)]27 }28 return v29 }30 getLCA := func(v, w int) int {31 if dep[v] > dep[w] {32 v, w = w, v33 }34 w = uptoDep(w, dep[v])35 if w == v {36 return v37 }38 for i := mx - 1; i >= 0; i-- {39 if pv, pw := pa[v][i], pa[w][i]; pv != pw {40 v, w = pv, pw41 }42 }43 return pa[v][0]44 }45 getDis := func(v, w int) int { return dep[v] + dep[w] - dep[getLCA(v, w)]*2 }46 47 end1, end2, diameter := 2, 3, 248 cur := 549 for range q {50 var v int51 Fscan(in, &v)52 pa[cur][0] = v53 for i := 0; i+1 < mx; i++ {54 pa[cur][i+1] = pa[pa[cur][i]][i]55 }56 pa[cur+1] = pa[cur]57 dep[cur] = dep[v] + 158 dep[cur+1] = dep[cur]59 60 if d := getDis(end1, cur); d > diameter {61 end2 = cur62 diameter = d63 } else if d = getDis(end2, cur); d > diameter {64 end1 = cur65 diameter = d66 }67 Fprintln(out, diameter)68 cur += 269 }70}71 7273