- 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
- 75 lines of Go from the credited upstream file 1941G.go.
- The implementation visibly relies on sequence storage.
- 1 loop block 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 . "fmt"5 "io"6)7 8func cf1941G(in io.Reader, out io.Writer) {9 var T, n, m, st, end int10 for Fscan(in, &T); T > 0; T-- {11 Fscan(in, &n, &m)12 type pair struct{ v, c int }13 g := map[pair][]pair{}14 add := func(v, c int) {15 p := pair{v, c}16 if g[p] == nil {17 q := pair{v, 0}18 g[p] = []pair{q}19 g[q] = append(g[q], p)20 }21 }22 for ; m > 0; m-- {23 var v, w, c int24 Fscan(in, &v, &w, &c)25 p := pair{v, c}26 q := pair{w, c}27 add(v, c)28 add(w, c)29 g[p] = append(g[p], q)30 g[q] = append(g[q], p)31 }32 Fscan(in, &st, &end)33 34 dis := make(map[pair]int, len(g))35 for p := range g {36 dis[p] = 1e937 }38 dis[pair{st, 0}] = 039 type vd struct{ v pair; d int }40 ql, qr := []vd{{pair{st, 0}, 0}}, []vd{}41 for {42 var p vd43 if len(ql) > 0 {44 ql, p = ql[:len(ql)-1], ql[len(ql)-1]45 } else {46 p, qr = qr[0], qr[1:]47 }48 v := p.v49 if v.v == end {50 Fprintln(out, p.d)51 break52 }53 if p.d > dis[v] {54 continue55 }56 for _, w := range g[v] {57 newD := p.d58 if v.c == 0 {59 newD++60 }61 if newD < dis[w] {62 dis[w] = newD63 if v.c > 0 {64 ql = append(ql, vd{w, newD})65 } else {66 qr = append(qr, vd{w, newD})67 }68 }69 }70 }71 }72}73 7475