- 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
- 61 lines of Go from the credited upstream file 938D.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 cf938D(_r io.Reader, _w io.Writer) {12 in := bufio.NewReader(_r)13 out := bufio.NewWriter(_w)14 defer out.Flush()15 16 var n, m, v, w, wt int17 Fscan(in, &n, &m)18 type nb struct{ to, wt int }19 g := make([][]nb, n+1)20 for ; m > 0; m-- {21 Fscan(in, &v, &w, &wt)22 g[v] = append(g[v], nb{w, wt * 2})23 g[w] = append(g[w], nb{v, wt * 2})24 }25 dis := make([]int, n+1)26 for i := 1; i <= n; i++ {27 Fscan(in, &wt)28 g[0] = append(g[0], nb{i, wt})29 dis[i] = 1e1830 }31 32 h := hp38{{}}33 for len(h) > 0 {34 p := heap.Pop(&h).(pair38)35 v := p.v36 if p.dis > dis[v] {37 continue38 }39 for _, e := range g[v] {40 w := e.to41 newD := p.dis + e.wt42 if newD < dis[w] {43 dis[w] = newD44 heap.Push(&h, pair38{newD, w})45 }46 }47 }48 for _, v := range dis[1:] {49 Fprint(out, v, " ")50 }51}52 5354type pair38 struct{ dis, v int }55type hp38 []pair3856func (h hp38) Len() int { return len(h) }57func (h hp38) Less(i, j int) bool { return h[i].dis < h[j].dis }58func (h hp38) Swap(i, j int) { h[i], h[j] = h[j], h[i] }59func (h *hp38) Push(v any) { *h = append(*h, v.(pair38)) }60func (h *hp38) Pop() (v any) { a := *h; *h, v = a[:len(a)-1], a[len(a)-1]; return }61