- 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
- 66 lines of Go from the credited upstream file 1409F.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 . "fmt"5 "io"6 "strings"7)8 910func CF1409F(in io.Reader, out io.Writer) {11 var n, K int12 var s, t string13 Fscan(in, &n, &K, &s, &t)14 if t[0] == t[1] {15 c := strings.Count(s, t[:1]) + K16 if c > n {17 c = n18 }19 Fprint(out, c*(c-1)/2)20 return21 }22 I := func(b bool) int {23 if b {24 return 125 }26 return 027 }28 max := func(a, b int) int {29 if a > b {30 return a31 }32 return b33 }34 35 dp := make([][][]int, n)36 for i := range dp {37 dp[i] = make([][]int, K+1)38 for j := range dp[i] {39 dp[i][j] = make([]int, n+1)40 for k := range dp[i][j] {41 dp[i][j][k] = -142 }43 }44 }45 var f func(p, left, c0 int) int46 f = func(p, left, c0 int) (res int) {47 if p == n {48 return49 }50 dv := &dp[p][left][c0]51 if *dv >= 0 {52 return *dv53 }54 defer func() { *dv = res }()55 res = I(s[p] == t[1])*c0 + f(p+1, left, c0+I(s[p] == t[0])) 56 if left > 0 {57 res = max(res, f(p+1, left-1, c0+1)) 58 res = max(res, c0+f(p+1, left-1, c0)) 59 }60 return61 }62 Fprint(out, f(0, K, 0))63}64 6566