- 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
- 63 lines of Go from the credited upstream file 1725M.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 "math"9)10 11func cf1725M(in io.Reader, _w io.Writer) {12 out := bufio.NewWriter(_w)13 defer out.Flush()14 var n, m int15 Fscan(in, &n, &m)16 type edge struct{ to, wt, inv int }17 g := make([][]edge, n)18 for ; m > 0; m-- {19 var v, w, wt int20 Fscan(in, &v, &w, &wt)21 v--22 w--23 g[v] = append(g[v], edge{w, wt, 0})24 g[w] = append(g[w], edge{v, wt, 1})25 }26 27 dis := make([][2]int, n)28 for i := 1; i < n; i++ {29 dis[i] = [2]int{math.MaxInt, math.MaxInt}30 }31 h := hp25{{}, {inv: 1}}32 for len(h) > 0 {33 p := heap.Pop(&h).(data25)34 if p.dis > dis[p.v][p.inv] {35 continue36 }37 for _, e := range g[p.v] {38 w, eInv := e.to, e.inv39 newD := p.dis + e.wt40 if (eInv == 1 || p.inv == 0) && newD < dis[w][eInv] {41 dis[w][eInv] = newD42 heap.Push(&h, data25{newD, w, eInv})43 }44 }45 }46 for _, d := range dis[1:] {47 res := min(d[0], d[1])48 if res == math.MaxInt {49 res = -150 }51 Fprint(out, res, " ")52 }53}54 5556type data25 struct{ dis, v, inv int }57type hp25 []data2558func (h hp25) Len() int { return len(h) }59func (h hp25) Less(i, j int) bool { return h[i].dis < h[j].dis }60func (h hp25) Swap(i, j int) { h[i], h[j] = h[j], h[i] }61func (h *hp25) Push(v any) { *h = append(*h, v.(data25)) }62func (h *hp25) Pop() (v any) { a := *h; *h, v = a[:len(a)-1], a[len(a)-1]; return }63