- 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
- 85 lines of Go from the credited upstream file 229B.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 "sort"10)11 1213func CF229B(_r io.Reader, out io.Writer) {14 in := bufio.NewReader(_r)15 var n, m, v, w, wt int16 Fscan(in, &n, &m)17 type nb struct{ to, wt int }18 g := make([][]nb, n)19 for ; m > 0; m-- {20 Fscan(in, &v, &w, &wt)21 v--22 w--23 g[v] = append(g[v], nb{w, wt})24 g[w] = append(g[w], nb{v, wt})25 }26 type seg struct{ l, r int }27 t := make([][]seg, n)28 for i := 0; i < n-1; i++ {29 pre := -230 for Fscan(in, &m); m > 0; m-- {31 Fscan(in, &v)32 if v > pre+1 {33 t[i] = append(t[i], seg{v, v})34 } else {35 t[i][len(t[i])-1].r = v36 }37 pre = v38 }39 }40 t[n-1] = nil41 42 dis := make([]int, n)43 for i := 1; i < n; i++ {44 dis[i] = math.MaxInt45 }46 if len(t[0]) > 0 && t[0][0].l == 0 {47 dis[0] = t[0][0].r + 148 }49 h := hp29{{0, dis[0]}}50 for len(h) > 0 {51 top := heap.Pop(&h).(pair29)52 v := top.v53 if top.dis > dis[v] {54 continue55 }56 for _, e := range g[v] {57 w, wt := e.to, e.wt58 newD := dis[v] + wt59 t := t[w]60 i := sort.Search(len(t), func(i int) bool { return t[i].r >= newD })61 if i < len(t) && t[i].l <= newD {62 newD = t[i].r + 163 }64 if newD < dis[w] {65 dis[w] = newD66 heap.Push(&h, pair29{w, newD})67 }68 }69 }70 if dis[n-1] == math.MaxInt {71 Fprint(out, -1)72 } else {73 Fprint(out, dis[n-1])74 }75}76 7778type pair29 struct{ v, dis int }79type hp29 []pair2980func (h hp29) Len() int { return len(h) }81func (h hp29) Less(i, j int) bool { return h[i].dis < h[j].dis }82func (h hp29) Swap(i, j int) { h[i], h[j] = h[j], h[i] }83func (h *hp29) Push(v interface{}) { *h = append(*h, v.(pair29)) }84func (h *hp29) Pop() (v interface{}) { a := *h; *h, v = a[:len(a)-1], a[len(a)-1]; return }85