Problem solution · Go

Codeforces 628D — Magic Numbers

Codeforces 628D — Magic Numbers: a Go solution using dynamic programming. Learn the idea, check the complexity, and read the full code, with credit to EndlessCheng Codeforces Go.

Technique
Dynamic programming
Source
EndlessCheng Codeforces Go
Length
72 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Dynamic programming

For Codeforces 628D — Magic Numbers, the implementation records answers for smaller states and reuses them to build the requested result without repeating work.

  1. Define precisely what one DP state represents.
  2. Establish the base cases before transitions are evaluated.
  3. 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.

Source

Code and credit

This code comes from EndlessCheng Codeforces Go by Σndless (EndlessCheng) and is used under the MIT licence.

Full codeCodeforces 628D — Magic Numbers · GoGo
Use this to learn the idea, then write your own version.
package main import (	"bufio"	. "fmt"	"io") // github.com/EndlessCheng/codeforces-gofunc CF628D(_r io.Reader, out io.Writer) {	in := bufio.NewReader(_r)	const mod int = 1e9 + 7	var m, D int	var lower, upper string	Fscan(in, &m, &D, &lower, &upper) 	calc := func(s string) int {		const lowerC, upperC byte = '0', '9'		n := len(s)		dp := make([][]int, n)		for i := range dp {			dp[i] = make([]int, m)			for j := range dp[i] {				dp[i][j] = -1			}		}		var f func(p, val int, limitUp bool) int		f = func(p, val int, limitUp bool) (res int) {			if p == n {				if val == 0 {					return 1				}				return			}			if !limitUp {				dv := &dp[p][val]				if *dv >= 0 {					return *dv				}				defer func() { *dv = res }()			}			up := upperC			if limitUp {				up = s[p]			}			for d := lowerC; d <= up; d++ {				if p&1 > 0 == (int(d&15) == D) {					cnt := f(p+1, (val*10+int(d&15))%m, limitUp && d == up)					res = (res + cnt) % mod				}			}			return		}		return f(0, 0, true)	}	ans := calc(upper) - calc(lower)	val := 0	for i, b := range lower {		if i&1 > 0 == (int(b&15) != D) {			goto end		}		val = (val*10 + int(b&15)) % m	}	if val == 0 {		ans++	}end:	Fprint(out, (ans%mod+mod)%mod)} //func main() { CF628D(os.Stdin, os.Stdout) } 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗