- 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
- 70 lines of Go from the credited upstream file 453B.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)7 89func CF453B(in io.Reader, out io.Writer) {10 primes := [...]int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53}11 const mx = len(primes)12 const mx2 = 1 << mx13 masks := [59]int{}14 for i := 2; i < 59; i++ {15 for j, p := range primes {16 if i%p == 0 {17 masks[i] |= 1 << j18 }19 }20 }21 abs := func(x int) int {22 if x < 0 {23 return -x24 }25 return x26 }27 28 var n, v int29 Fscan(in, &n)30 dp := make([][mx2]int, n+1)31 for i := range dp {32 for j := 0; j < mx2; j++ {33 dp[i][j] = 1e934 }35 }36 dp[0][0] = 037 type pair struct{ j, v int }38 fa := make([][mx2]pair, n+1)39 for i := 1; i <= n; i++ {40 Fscan(in, &v)41 for j := 1; j == 1 || j < v*2-1; j++ {42 m := masks[j]43 c := m ^ (mx2 - 1)44 for sub, ok := c, true; ok; ok = sub != c {45 if s := dp[i-1][sub] + abs(j-v); s < dp[i][m|sub] {46 dp[i][m|sub] = s47 fa[i][m|sub] = pair{sub, j}48 }49 sub = (sub - 1) & c50 }51 }52 }53 miJ := 054 for j, v := range dp[n] {55 if v < dp[n][miJ] {56 miJ = j57 }58 }59 ans := make([]int, n)60 for i, j := n, miJ; i > 0; i-- {61 ans[i-1] = fa[i][j].v62 j = fa[i][j].j63 }64 for _, v := range ans {65 Fprint(out, v, " ")66 }67}68 6970