- 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
- 72 lines of Go from the credited upstream file 1209F.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 cf1209F(_r io.Reader, _w io.Writer) {11 in := bufio.NewReader(_r)12 out := bufio.NewWriter(_w)13 defer out.Flush()14 15 var n, m int16 Fscan(in, &n, &m)17 n0 := n18 type nb struct{ to, wt int }19 g := [1e6][]nb{}20 add := func(v, w, x int) {21 for ; x > 9; x /= 10 {22 g[n] = []nb{{w, x % 10}}23 w = n24 n++25 }26 g[v] = append(g[v], nb{w, x})27 }28 for i := 1; i <= m; i++ {29 var v, w int30 Fscan(in, &v, &w)31 v--32 w--33 add(v, w, i)34 add(w, v, i)35 }36 37 dis := make([]int, n)38 vis := make([]bool, n)39 vis[0] = true40 q := [][]int{{0}}41 for len(q) > 0 {42 vs := q[0]43 q = q[1:]44 type edge struct{ from, to int }45 nxt := [10][]edge{}46 for _, v := range vs {47 for _, e := range g[v] {48 nxt[e.wt] = append(nxt[e.wt], edge{v, e.to})49 }50 }51 for wt, es := range nxt {52 ws := []int{}53 for _, e := range es {54 w := e.to55 if !vis[w] {56 vis[w] = true57 dis[w] = (dis[e.from]*10 + wt) % 1_000_000_00758 ws = append(ws, w)59 }60 }61 if len(ws) > 0 {62 q = append(q, ws)63 }64 }65 }66 for _, v := range dis[1:n0] {67 Fprintln(out, v)68 }69}70 7172