- 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
- 79 lines of Go from the credited upstream file 20C.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 . "container/heap"6 . "fmt"7 "io"8)9 10type pr20 struct {11 d int6412 v int13}14type hp20 []pr2015 16func (h hp20) Len() int { return len(h) }17func (h hp20) Less(i, j int) bool { return h[i].d < h[j].d }18func (h hp20) Swap(i, j int) { h[i], h[j] = h[j], h[i] }19func (h *hp20) Push(v interface{}) { *h = append(*h, v.(pr20)) }20func (h *hp20) Pop() (v interface{}) { a := *h; *h, v = a[:len(a)-1], a[len(a)-1]; return }21 2223func CF20C(_r io.Reader, _w io.Writer) {24 in := bufio.NewReader(_r)25 out := bufio.NewWriter(_w)26 defer out.Flush()27 type edge struct {28 to int29 w int6430 }31 32 var n, m, v, w int33 var weight int6434 Fscan(in, &n, &m)35 g := make([][]edge, n+1)36 for ; m > 0; m-- {37 Fscan(in, &v, &w, &weight)38 g[v] = append(g[v], edge{w, weight})39 g[w] = append(g[w], edge{v, weight})40 }41 42 const inf int64 = 1e1843 dist := make([]int64, n+1)44 for i := range dist {45 dist[i] = inf46 }47 dist[1] = 048 fa := make([]int, n+1)49 h := hp20{{0, 1}}50 for len(h) > 0 {51 p := Pop(&h).(pr20)52 d, v := p.d, p.v53 if dist[v] < d {54 continue55 }56 for _, e := range g[v] {57 w := e.to58 if newD := d + e.w; newD < dist[w] {59 dist[w] = newD60 fa[w] = v61 Push(&h, pr20{newD, w})62 }63 }64 }65 if dist[n] == inf {66 Fprint(out, -1)67 return68 }69 path := []int{}70 for x := n; x > 0; x = fa[x] {71 path = append(path, x)72 }73 for i := len(path) - 1; i >= 0; i-- {74 Fprint(out, path[i], " ")75 }76}77 7879