- 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
- 65 lines of Go from the credited upstream file 1790F.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 CF1790F(_r io.Reader, _w io.Writer) {11 in := bufio.NewReader(_r)12 out := bufio.NewWriter(_w)13 defer out.Flush()14 15 var T, n, v, w int16 for Fscan(in, &T); T > 0; T-- {17 Fscan(in, &n)18 c := make([]int, n)19 for i := range c {20 Fscan(in, &c[i])21 c[i]--22 }23 g := make([][]int, n)24 for i := 1; i < n; i++ {25 Fscan(in, &v, &w)26 v--27 w--28 g[v] = append(g[v], w)29 g[w] = append(g[w], v)30 }31 32 pa := make([]int, n)33 pa[0] = -134 var f func(int)35 f = func(v int) {36 for _, w := range g[v] {37 if w != pa[v] {38 pa[w] = v39 f(w)40 }41 }42 }43 f(0)44 45 mn := n + 146 dis := make([]int, n)47 for i := range dis {48 dis[i] = n + 149 }50 for i, v := range c {51 for step := 0; v >= 0 && step < mn; step++ {52 mn = min(mn, dis[v]+step)53 dis[v] = min(dis[v], step)54 v = pa[v]55 }56 if i > 0 {57 Fprint(out, mn, " ")58 }59 }60 Fprintln(out)61 }62}63 6465