Problem solution · Go

Codeforces 1073E — Segment Sum

Codeforces 1073E — Segment Sum: a Go solution using depth-first search. Learn the idea, check the complexity, and read the full code, with credit to EndlessCheng Codeforces Go.

Technique
Depth-first search
Source
EndlessCheng Codeforces Go
Length
70 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

Depth-first search

For Codeforces 1073E — Segment Sum, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.

  1. Define the state carried into one recursive or stack frame.
  2. Mark or choose the current state before exploring children.
  3. Combine child results or undo the choice when the branch finishes.

Code notes

  • 70 lines of Go from the credited upstream file 1073E.go.
  • The implementation visibly relies on sequence storage, cached states.
  • No explicit loop blocks detected, together with recursive traversal.

Complexity

Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.

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 1073E — Segment Sum · GoGo
Use this to learn the idea, then write your own version.
package main import (	. "fmt"	"io"	"math"	"math/bits") // https://github.com/EndlessChengfunc cf1073E(in io.Reader, out io.Writer) {	const mod = 998244353	var lowS, highS string	var k int	Fscan(in, &lowS, &highS, &k)	n := len(highS)	diffLH := n - len(lowS)	type pair struct{ cnt, sum int }	memo := make([][1 << 10]pair, n)	for i := range memo {		for j := range memo[i] {			memo[i][j].cnt = -1		}	} 	var dfs func(int, int, bool, bool) pair	dfs = func(i, mask int, limitLow, limitHigh bool) (res pair) {		if i == n {			return pair{1, 0}		}		if !limitLow && !limitHigh {			dv := &memo[i][mask]			if dv.cnt >= 0 {				return *dv			}			defer func() { *dv = res }()		} 		lo := 0		if limitLow && i >= diffLH {			lo = int(lowS[i-diffLH] - '0')		}		hi := 9		if limitHigh {			hi = int(highS[i] - '0')		} 		d := lo		if limitLow && i < diffLH {			res = dfs(i+1, 0, true, false)			d = 1		} 		for ; d <= hi; d++ {			newMask := mask | 1<<d			if bits.OnesCount(uint(newMask)) > k {				continue			}			sub := dfs(i+1, newMask, limitLow && d == lo, limitHigh && d == hi)			res.cnt = (res.cnt + sub.cnt) % mod			v := d * int(math.Pow10(n-1-i)) % mod			res.sum = (res.sum + sub.sum + v*sub.cnt) % mod		}		return	}	Fprint(out, dfs(0, 0, true, true).sum)} //func main() { cf1073E(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 ↗