- Define precisely what one DP state represents.
- Establish the base cases before transitions are evaluated.
- Process states in dependency order and combine only already-known values.
Code notes
- 76 lines of Go from the credited upstream file 487B.go.
- The implementation visibly relies on sequence storage, cached states.
- No explicit loop blocks detected.
Complexity
Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.
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 . "fmt"6 "io"7)8 910type data87 struct{ val, del int }11type mq87 struct {12 data []data8713 size int14 less func(a, b data87) bool15}16 17func (q *mq87) push(v int) {18 q.size++19 d := data87{v, 1}20 for len(q.data) > 0 && q.less(d, q.data[len(q.data)-1]) {21 d.del += q.data[len(q.data)-1].del22 q.data = q.data[:len(q.data)-1]23 }24 q.data = append(q.data, d)25}26 27func (q *mq87) pop() {28 q.size--29 if q.data[0].del > 1 {30 q.data[0].del--31 } else {32 q.data = q.data[1:]33 }34}35 36func (q mq87) top() int {37 return q.data[0].val38}39 40func CF487B(_r io.Reader, out io.Writer) {41 in := bufio.NewReader(_r)42 var n, maxD, minL, v int43 Fscan(in, &n, &maxD, &minL)44 small := mq87{less: func(a, b data87) bool { return a.val <= b.val }}45 big := mq87{less: func(a, b data87) bool { return a.val >= b.val }}46 dpMQ := mq87{less: func(a, b data87) bool { return a.val <= b.val }}47 dp := make([]int, n+1)48 for i := range dp {49 dp[i] = 1e950 }51 dp[0] = 052 for i := 1; i <= n; i++ {53 Fscan(in, &v)54 small.push(v)55 big.push(v)56 if i < minL {57 continue58 }59 dpMQ.push(dp[i-minL])60 for dpMQ.size > 0 && big.top()-small.top() > maxD {61 small.pop()62 big.pop()63 dpMQ.pop()64 }65 if dpMQ.size > 0 {66 dp[i] = dpMQ.top() + 167 }68 }69 if dp[n] >= 1e9 { 70 dp[n] = -171 }72 Fprint(out, dp[n])73}74 7576