- 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
- 89 lines of Go from the credited upstream file 1936C.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 "slices"9)10 1112func cf1936C(in io.Reader, _w io.Writer) {13 out := bufio.NewWriter(_w)14 defer out.Flush()15 var T, n, m, ci int16 for Fscan(in, &T); T > 0; T-- {17 Fscan(in, &n, &m)18 19 st := n * m20 end := st + n - 121 type edge struct{ to, wt int }22 g := make([][]edge, end+1)23 24 for i := range n {25 Fscan(in, &ci)26 v := n*m + i27 for w := i * m; w < (i+1)*m; w++ {28 g[v] = append(g[v], edge{w, 0})29 g[w] = append(g[w], edge{v, ci})30 }31 }32 33 a := make([][]int, n)34 for i := range a {35 a[i] = make([]int, m)36 for j := range a[i] {37 Fscan(in, &a[i][j])38 }39 }40 type pair struct{ v, i int }41 p := make([]pair, n)42 for j := range m {43 for i, r := range a {44 p[i] = pair{r[j], i}45 }46 slices.SortFunc(p, func(a, b pair) int { return a.v - b.v })47 for i := range n - 1 {48 v := p[i].i*m + j49 w := p[i+1].i*m + j50 g[v] = append(g[v], edge{w, 0})51 g[w] = append(g[w], edge{v, p[i+1].v - p[i].v})52 }53 }54 55 dis := make([]int, len(g))56 for i := range dis {57 dis[i] = 1e1858 }59 dis[st] = 060 h := hp36{{0, st}}61 for len(h) > 0 {62 p := heap.Pop(&h).(vd36)63 if p.d > dis[p.v] {64 continue65 }66 for _, e := range g[p.v] {67 w := e.to68 d := p.d + e.wt69 if d < dis[w] {70 dis[w] = d71 heap.Push(&h, vd36{d, w})72 }73 }74 }75 Fprintln(out, dis[end])76 }77}78 7980 81type vd36 struct{ d, v int }82type hp36 []vd3683 84func (h hp36) Len() int { return len(h) }85func (h hp36) Less(i, j int) bool { return h[i].d < h[j].d }86func (h hp36) Swap(i, j int) { h[i], h[j] = h[j], h[i] }87func (h *hp36) Push(v any) { *h = append(*h, v.(vd36)) }88func (h *hp36) Pop() (v any) { a := *h; *h, v = a[:len(a)-1], a[len(a)-1]; return }89