Problem solution · Go

Codeforces 815C — Karen and Supermarket

Codeforces 815C — Karen and Supermarket: 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
55 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 815C — Karen and Supermarket, 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

  • 55 lines of Go from the credited upstream file 815C.go.
  • The implementation visibly relies on sequence storage.
  • 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 815C — Karen and Supermarket · GoGo
Use this to learn the idea, then write your own version.
package main import (	. "fmt"	"io") // https://github.com/EndlessChengfunc cf815C(in io.Reader, out io.Writer) {	var n, b, v int	Fscan(in, &n, &b)	type pair struct{ nc, c int } // 不优惠,优惠	a := make([]pair, n)	g := make([][]int, n)	Fscan(in, &a[0].nc, &a[0].c)	for w := 1; w < n; w++ {		Fscan(in, &a[w].nc, &a[w].c, &v)		g[v-1] = append(g[v-1], w)	} 	var dfs func(int) ([]pair, int)	dfs = func(v int) ([]pair, int) {		f := make([]pair, n+1)		f[0].c = 1e18		f[1] = pair{a[v].nc, a[v].nc - a[v].c}		for i := 2; i <= n; i++ {			f[i] = pair{1e18, 1e18}		}		size := 1		for _, w := range g[v] {			fw, sz := dfs(w)			for j := size; j >= 0; j-- {				for k, p := range fw {					f[j+k].nc = min(f[j+k].nc, f[j].nc+p.nc)					if j > 0 { // 根节点必选						f[j+k].c = min(f[j+k].c, f[j].c+min(p.nc, p.c))					}				}			}			size += sz		}		return f[:size+1], size	} 	f, _ := dfs(0)	for i := n; ; i-- {		if min(f[i].nc, f[i].c) <= b {			Fprint(out, i)			return		}	}} //func main() { cf815C(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 ↗