- 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
- 87 lines of Go from the credited upstream file 1106E.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 1011type dw6 struct{ d, w int }12type pair6 struct {13 dw614 i int15}16type mh6 []*pair617 18func (h mh6) Len() int { return len(h) }19func (h mh6) Less(i, j int) bool { a, b := h[i], h[j]; return a.w > b.w || a.w == b.w && a.d > b.d }20func (h mh6) Swap(i, j int) { h[i], h[j] = h[j], h[i]; h[i].i = i; h[j].i = j }21func (h *mh6) Push(v interface{}) { *h = append(*h, v.(*pair6)) }22func (h *mh6) Pop() interface{} { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v }23func (h *mh6) push(e dw6) *pair6 { p := &pair6{e, len(*h)}; heap.Push(h, p); return p }24 25func CF1106E(_r io.Reader, out io.Writer) {26 in := bufio.NewReader(_r)27 min := func(a, b int64) int64 {28 if a < b {29 return a30 }31 return b32 }33 34 var n, m, k, s, t, d, w int35 Fscan(in, &n, &m, &k)36 es := make([][]dw6, n+1)37 for ; k > 0; k-- {38 Fscan(in, &s, &t, &d, &w)39 es[s] = append(es[s], dw6{d, w})40 if t < n {41 es[t+1] = append(es[t+1], dw6{-d, w})42 }43 }44 45 next := make([]dw6, n+1)46 h := mh6{}47 ptr := map[dw6][]*pair6{}48 for i, es := range es {49 for _, e := range es {50 if e.d > 0 {51 ptr[e] = append(ptr[e], h.push(e))52 } else {53 e.d = -e.d54 heap.Remove(&h, ptr[e][0].i)55 ptr[e] = ptr[e][1:]56 }57 }58 if len(h) > 0 {59 next[i] = h[0].dw660 } else {61 next[i].d = i62 }63 }64 65 ans := int64(1e18)66 cur := make([]int64, n+2)67 for i := range cur {68 cur[i] = 1e1869 }70 cur[1] = 071 for k := 0; k <= m; k++ {72 nxt := make([]int64, n+2)73 for i := range nxt {74 nxt[i] = 1e1875 }76 for i := 1; i <= n; i++ {77 nxt[i+1] = min(nxt[i+1], cur[i])78 cur[next[i].d+1] = min(cur[next[i].d+1], cur[i]+int64(next[i].w))79 }80 ans = min(ans, cur[n+1])81 cur = nxt82 }83 Fprint(out, ans)84}85 8687