- 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
- 78 lines of Go from the credited upstream file 545E.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 1011func cf545E(in io.Reader, _w io.Writer) {12 out := bufio.NewWriter(_w)13 defer out.Flush()14 var n, m, st int15 Fscan(in, &n, &m)16 type edge struct{ to, wt, i int }17 g := make([][]edge, n)18 for i := 1; i <= m; i++ {19 var v, w, wt int20 Fscan(in, &v, &w, &wt)21 v--22 w--23 g[v] = append(g[v], edge{w, wt, i})24 g[w] = append(g[w], edge{v, wt, i})25 }26 Fscan(in, &st)27 st--28 29 type pair struct{ wt, i int }30 from := make([]pair, n)31 dis := make([]int, n)32 for i := range dis {33 dis[i] = 1e1834 }35 dis[st] = 036 h := hp45{{0, st}}37 for len(h) > 0 {38 p := heap.Pop(&h).(vd45)39 v := p.v40 d := p.dis41 if d > dis[v] {42 continue43 }44 for _, e := range g[v] {45 w, wt := e.to, e.wt46 newD := d + wt47 if newD < dis[w] {48 dis[w] = newD49 heap.Push(&h, vd45{newD, w})50 from[w] = pair{wt, e.i}51 } else if newD == dis[w] {52 from[w] = pair{wt, e.i}53 }54 }55 }56 57 ans := 058 for _, p := range from {59 ans += p.wt60 }61 Fprintln(out, ans)62 for i, p := range from {63 if i != st {64 Fprint(out, p.i, " ")65 }66 }67}68 6970 71type vd45 struct{ dis, v int }72type hp45 []vd4573func (h hp45) Len() int { return len(h) }74func (h hp45) Less(i, j int) bool { return h[i].dis < h[j].dis }75func (h hp45) Swap(i, j int) { h[i], h[j] = h[j], h[i] }76func (h *hp45) Push(v any) { *h = append(*h, v.(vd45)) }77func (h *hp45) Pop() (v any) { a := *h; *h, v = a[:len(a)-1], a[len(a)-1]; return }78