- 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
- 65 lines of Go from the credited upstream file 1221D.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 9func Sol1221D(reader io.Reader, writer io.Writer) {10 const inf int64 = 2e1811 min := func(a, b int64) int64 {12 if a <= b {13 return a14 }15 return b16 }17 mins := func(vals ...int64) int64 {18 ans := vals[0]19 for _, val := range vals[1:] {20 if val < ans {21 ans = val22 }23 }24 return ans25 }26 27 in := bufio.NewReader(reader)28 out := bufio.NewWriter(writer)29 defer out.Flush()30 31 var dp [2][3]int6432 var t int33 for Fscan(in, &t); t > 0; t-- {34 var n int35 Fscan(in, &n)36 h := make([]int, n)37 costs := make([]int, n)38 for i := range h {39 Fscan(in, &h[i], &costs[i])40 }41 42 row := 043 dp[0][0] = 044 dp[0][1] = int64(costs[0])45 dp[0][2] = int64(2 * costs[0])46 for i := 1; i < n; i++ {47 row ^= 148 for d0 := 0; d0 < 3; d0++ {49 ans := inf50 for d1 := 0; d1 < 3; d1++ {51 if h[i]+d0 != h[i-1]+d1 {52 ans = min(ans, dp[row^1][d1]+int64(d0*costs[i]))53 }54 }55 dp[row][d0] = ans56 }57 }58 Fprintln(out, mins(dp[row][:]...))59 }60}61 62636465