- 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
- 69 lines of Go from the credited upstream file 771D.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 "sort"7)8 910func cf771D(in io.Reader, out io.Writer) {11 n, s := 0, ""12 Fscan(in, &n, &s)13 var pv, pk, pa []int14 for i, b := range s {15 if b == 'V' {16 pv = append(pv, i)17 } else if b == 'K' {18 pk = append(pk, i)19 } else {20 pa = append(pa, i)21 }22 }23 dp := make([][][][2]int, len(pv)+1)24 for i := range dp {25 dp[i] = make([][][2]int, len(pk)+1)26 for j := range dp[i] {27 dp[i][j] = make([][2]int, len(pa)+1)28 for k := range dp[i][j] {29 dp[i][j][k] = [2]int{-1, -1}30 }31 }32 }33 var f func(int, int, int, int) int34 f = func(i, j, k, preV int) (res int) {35 if i+j+k == n {36 return37 }38 ptr := &dp[i][j][k][preV]39 if *ptr >= 0 {40 return *ptr41 }42 43 res = 1e944 if i < len(pv) {45 p := pv[i]46 r := j - sort.SearchInts(pk[:j], p)47 r += k - sort.SearchInts(pa[:k], p)48 res = min(res, f(i+1, j, k, 1)+r)49 }50 if preV == 0 && j < len(pk) {51 p := pk[j]52 r := i - sort.SearchInts(pv[:i], p)53 r += k - sort.SearchInts(pa[:k], p)54 res = min(res, f(i, j+1, k, 0)+r)55 }56 if k < len(pa) {57 p := pa[k]58 r := i - sort.SearchInts(pv[:i], p)59 r += j - sort.SearchInts(pk[:j], p)60 res = min(res, f(i, j, k+1, 0)+r)61 }62 *ptr = res63 return64 }65 Fprint(out, f(0, 0, 0, 0))66}67 6869