- 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
- 74 lines of Go from the credited upstream file 1927G.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 cf1927G(_r io.Reader, out io.Writer) {11 in := bufio.NewReader(_r)12 var T, n int13 for Fscan(in, &T); T > 0; T-- {14 Fscan(in, &n)15 a := make([]int, n, n+1)16 for i := range a {17 Fscan(in, &a[i])18 }19 a = append(a, 1)20 21 dp := make([][][]int, n)22 for i := range dp {23 dp[i] = make([][]int, n+1)24 for j := range dp[i] {25 dp[i][j] = make([]int, n+1)26 for k := range dp[i][j] {27 dp[i][j][k] = -128 }29 }30 }31 var f func(int, int, int) int32 f = func(i, j, doneL int) int {33 if doneL == 0 {34 return 035 }36 if i < 0 {37 return 1e938 }39 p := &dp[i][j][doneL]40 if *p != -1 {41 return *p42 }43 44 45 46 47 48 res := f(i-1, j, doneL)49 50 51 if j == n {52 if i >= doneL-1 {53 res = min(res, f(i-1, n, min(doneL, max(i-a[i]+1, 0)))+1)54 } else {55 res = min(res, f(i-1, i, doneL)+1) 56 }57 } else if i >= j-a[j] && i-a[i] < j-a[j] {58 res = min(res, f(i-1, i, doneL)+1) 59 }60 61 62 if i < doneL && i+a[i] >= doneL {63 res = min(res, f(i-1, n, min(i, max(j-a[j]+1, 0)))+1)64 }65 66 *p = res67 return res68 }69 Fprintln(out, f(n-1, n, n))70 }71}72 7374