- 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
- 80 lines of Go from the credited upstream file 1517D.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 "strings"8)9 1011func CF1517D(_r io.Reader, _w io.Writer) {12 in := bufio.NewReader(_r)13 out := bufio.NewWriter(_w)14 defer out.Flush()15 type edge struct{ x, y, wt int }16 17 var n, m, k, wt int18 Fscan(in, &n, &m, &k)19 if k&1 > 0 {20 for s := strings.Repeat("-1 ", m); n > 0; n-- {21 Fprintln(out, s)22 }23 return24 }25 k /= 226 g := make([][][]edge, n)27 for i := range g {28 g[i] = make([][]edge, m)29 for j := 1; j < m; j++ {30 Fscan(in, &wt)31 g[i][j-1] = append(g[i][j-1], edge{i, j, wt})32 g[i][j] = append(g[i][j], edge{i, j - 1, wt})33 }34 }35 for i := 1; i < n; i++ {36 for j := 0; j < m; j++ {37 Fscan(in, &wt)38 g[i-1][j] = append(g[i-1][j], edge{i, j, wt})39 g[i][j] = append(g[i][j], edge{i - 1, j, wt})40 }41 }42 43 dp := make([][][]int, n)44 for i := range dp {45 dp[i] = make([][]int, m)46 for j := range dp[i] {47 dp[i][j] = make([]int, k+1)48 for k := range dp[i][j] {49 dp[i][j][k] = -150 }51 }52 }53 var f func(x, y, k int) int54 f = func(x, y, k int) (res int) {55 if k == 0 {56 return57 }58 dv := &dp[x][y][k]59 if *dv != -1 {60 return *dv61 }62 defer func() { *dv = res }()63 res = 1e964 for _, e := range g[x][y] {65 if r := f(e.x, e.y, k-1) + e.wt; r < res {66 res = r67 }68 }69 return70 }71 for i := 0; i < n; i++ {72 for j := 0; j < m; j++ {73 Fprint(out, f(i, j, k)*2, " ")74 }75 Fprintln(out)76 }77}78 7980