- 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
- 72 lines of Go from the credited upstream file 628D.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 CF628D(_r io.Reader, out io.Writer) {11 in := bufio.NewReader(_r)12 const mod int = 1e9 + 713 var m, D int14 var lower, upper string15 Fscan(in, &m, &D, &lower, &upper)16 17 calc := func(s string) int {18 const lowerC, upperC byte = '0', '9'19 n := len(s)20 dp := make([][]int, n)21 for i := range dp {22 dp[i] = make([]int, m)23 for j := range dp[i] {24 dp[i][j] = -125 }26 }27 var f func(p, val int, limitUp bool) int28 f = func(p, val int, limitUp bool) (res int) {29 if p == n {30 if val == 0 {31 return 132 }33 return34 }35 if !limitUp {36 dv := &dp[p][val]37 if *dv >= 0 {38 return *dv39 }40 defer func() { *dv = res }()41 }42 up := upperC43 if limitUp {44 up = s[p]45 }46 for d := lowerC; d <= up; d++ {47 if p&1 > 0 == (int(d&15) == D) {48 cnt := f(p+1, (val*10+int(d&15))%m, limitUp && d == up)49 res = (res + cnt) % mod50 }51 }52 return53 }54 return f(0, 0, true)55 }56 ans := calc(upper) - calc(lower)57 val := 058 for i, b := range lower {59 if i&1 > 0 == (int(b&15) != D) {60 goto end61 }62 val = (val*10 + int(b&15)) % m63 }64 if val == 0 {65 ans++66 }67end:68 Fprint(out, (ans%mod+mod)%mod)69}70 7172