Problem solution · Go

Codeforces 757D — Felicity's Big Secret Revealed

Codeforces 757D — Felicity's Big Secret Revealed: 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
60 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 757D — Felicity's Big Secret Revealed, 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

  • 60 lines of Go from the credited upstream file 757D.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 757D — Felicity's Big Secret Revealed · GoGo
Use this to learn the idea, then write your own version.
package main import (	. "fmt"	"io") // github.com/EndlessCheng/codeforces-gofunc CF757D(in io.Reader, out io.Writer) {	const mod int = 1e9 + 7	const mx = 20	var n, ans int	var s []byte	Fscan(in, &n, &s)	for i := range s {		s[i] &= 1	}	// 注意,不要写 make([][1<<mx]int, n),由于 Go 内存管理的原因,会将申请的内存塞到一个不小于所需空间的 2 的幂次的内存块中	// 在 n=75 时,所需空间为 300MB,因此会塞到 512MB 大小的内存中,但是申请这部分内存又会导致 MLE	// 下面的写法,每次只申请 4MB 的内存,最后实际使用内存约为 334MB https://codeforces.com/contest/757/submission/124971542	// 另一种写法是声明一个全局变量 var dp [75][1<<mx]int,最后实际使用内存约为 311MB https://codeforces.com/contest/757/submission/124969909	dp := make([][]int, n)	for i := range dp {		dp[i] = make([]int, 1<<mx)		for j := range dp[i] {			dp[i][j] = -1		}	}	var f func(int, int) int	f = func(p, mask int) (res int) {		if mask&(mask+1) == 0 && mask > 0 {			res = 1		}		if p == n {			return		}		dv := &dp[p][mask]		if *dv != -1 {			return *dv		}		defer func() { *dv = res }()		for j, v := p, byte(0); j < n; j++ {			v = v<<1 | s[j]			if v > mx {				break			}			if v > 0 {				res = (res + f(j+1, mask|1<<(v-1))) % mod			}		}		return	}	for i := range s {		ans = (ans + f(i, 0)) % mod	}	Fprint(out, ans)} //func main() { CF757D(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 ↗