Problem solution · Go

Codeforces 1065F — Up and Down the Tree

Codeforces 1065F — Up and Down the Tree: 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
47 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 1065F — Up and Down the Tree, 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

  • 47 lines of Go from the credited upstream file 1065F.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 1065F — Up and Down the Tree · GoGo
Use this to learn the idea, then write your own version.
package main import (	. "fmt"	"io") // 把 DFS 写在外面可以避免 MLE // https://github.com/EndlessChengfunc cf1065F(in io.Reader, out io.Writer) {	var n, k int	Fscan(in, &n, &k)	g := make([][]int, n)	for w := 1; w < n; w++ {		var p int		Fscan(in, &p)		g[p-1] = append(g[p-1], w)	} 	// base = 能回到 v 时,可以访问的叶子数	// ex = 无法回到 v 时,相比 base 额外访问的叶子数	var dfs func(int, int) (int, int, int)	dfs = func(v, dep int) (minUpDep, base, ex int) {		if g[v] == nil {			return max(dep-k, 0), 1, 0		}		minUpDep = n		for _, w := range g[v] {			up, b, e := dfs(w, dep+1)			if up > dep { // 进入 w 无法回到 v				ex = max(ex, b+e) // ex 是 w 里的全部			} else { // 进入 w 可以回到 v				minUpDep = min(minUpDep, up)				// 分开统计 b 和 e				base += b				ex = max(ex, e)			}		}		return	}	_, base, ex := dfs(0, 0)	Fprint(out, base+ex)} //func main() { cf1065F(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 ↗