- 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
- 78 lines of Go from the credited upstream file 711C.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 910func CF711C(_r io.Reader, out io.Writer) {11 min := func(a, b int64) int64 {12 if a < b {13 return a14 }15 return b16 }17 in := bufio.NewReader(_r)18 var n, m, tar int19 Fscan(in, &n, &m, &tar)20 a := make([]int, n)21 for i := range a {22 Fscan(in, &a[i])23 }24 cost := make([][]int64, n)25 for i := range cost {26 cost[i] = make([]int64, m)27 for j := range cost[i] {28 Fscan(in, &cost[i][j])29 }30 }31 32 const inf int64 = 1e1833 ans := inf34 dp := make([][][]int64, n)35 for i := range dp {36 dp[i] = make([][]int64, n+1)37 for j := range dp[i] {38 dp[i][j] = make([]int64, m)39 for k := range dp[i][j] {40 dp[i][j][k] = inf41 }42 }43 }44 if c := a[0]; c > 0 {45 dp[0][1][c-1] = 046 } else {47 dp[0][1] = cost[0]48 }49 for i := 1; i < n; i++ {50 for b := 1; b <= n; b++ {51 for c, cst := range cost[i] {52 if a[i] > 0 {53 if c != a[i]-1 {54 continue55 }56 cst = 057 }58 for pc := 0; pc < m; pc++ {59 bb := b60 if c != pc {61 bb--62 }63 dp[i][b][c] = min(dp[i][b][c], dp[i-1][bb][pc]+cst)64 }65 }66 }67 }68 for _, v := range dp[n-1][tar] {69 ans = min(ans, v)70 }71 if ans == inf {72 ans = -173 }74 Fprint(out, ans)75}76 7778