- 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
- 71 lines of Go from the credited upstream file 1846G.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 "container/heap"5 . "fmt"6 "io"7)8 910func bin46(s string) (a int) {11 for i, b := range s {12 a |= int(b&1) << i13 }14 return15}16 17func cf1846G(in io.Reader, out io.Writer) {18 var T, n, m int19 var s, t string20o:21 for Fscan(in, &T); T > 0; T-- {22 Fscan(in, &n, &m, &s)23 st := bin46(s)24 a := make([]struct{ d, s, t int }, m)25 for i := range a {26 Fscan(in, &a[i].d, &s, &t)27 a[i].s = bin46(s)28 a[i].t = bin46(t)29 }30 31 dis := make([]int, 1<<n)32 for i := range dis {33 dis[i] = 1e934 }35 dis[st] = 036 h := hp46{{0, st}}37 for len(h) > 0 {38 p := heap.Pop(&h).(pair46)39 d := p.d40 v := p.v41 if v == 0 {42 Fprintln(out, d)43 continue o44 }45 if d > dis[v] {46 continue47 }48 for _, t := range a {49 newD := d + t.d50 w := v&^t.s | t.t51 if newD < dis[w] {52 dis[w] = newD53 heap.Push(&h, pair46{newD, w})54 }55 }56 }57 Fprintln(out, -1)58 }59}60 6162 63type pair46 struct{ d, v int }64type hp46 []pair4665 66func (h hp46) Len() int { return len(h) }67func (h hp46) Less(i, j int) bool { return h[i].d < h[j].d }68func (h hp46) Swap(i, j int) { h[i], h[j] = h[j], h[i] }69func (h *hp46) Push(v any) { *h = append(*h, v.(pair46)) }70func (h *hp46) Pop() (v any) { a := *h; *h, v = a[:len(a)-1], a[len(a)-1]; return }71