Problem solution · Go

Codeforces 908G — New Year and Original Order

Codeforces 908G — New Year and Original Order: 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
65 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 908G — New Year and Original Order, 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

  • 65 lines of Go from the credited upstream file 908G.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 908G — New Year and Original Order · GoGo
Use this to learn the idea, then write your own version.
package main import (	. "fmt"	"io") // https://github.com/EndlessChengfunc cf908G(in io.Reader, out io.Writer) {	const mod = 1_000_000_007	var s string	Fscan(in, &s)	n := len(s)	ans := 0	type pair struct{ f, g int }	memo := make([]pair, n)	for tar := 1; tar < 10; tar++ {		for i := range memo {			memo[i].f = -1		}		var f func(int, bool) pair		f = func(i int, isLimit bool) (res pair) {			if i == n {				return pair{0, 1}			}			if !isLimit {				p := &memo[i]				if p.f >= 0 {					return *p				}				defer func() { *p = res }()			} 			up := 9			if isLimit {				up = int(s[i] - '0')			} 			for d := range up + 1 {				p := f(i+1, isLimit && d == up)				if d < tar {					res.f += p.f					res.g += p.g				} else if d == tar {					// 比如 s="23",tar=1					// p.f*10 的意思是,第一位填 1,会把第二位填的 1(排序后)变成 10 					// p.g 的意思是,第一位填 1,那么第二位填 0~9 对第一位的 1 的影响(乘积系数)是 1,1,10,10,...,10,一共是 82,这个就是 p.g					res.f += p.f*10 + p.g					res.g += p.g				} else {					res.f += p.f * 10					res.g += p.g * 10				}			}			res.f %= mod			res.g %= mod			return		}		ans += f(0, true).f * tar	}	Fprint(out, ans%mod)} //func main() { cf908G(bufio.NewReader(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 ↗