Problem solution · Go

Codeforces 1914F — Programming Competition

Codeforces 1914F — Programming Competition: 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
69 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 1914F — Programming Competition, 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

  • 69 lines of Go from the credited upstream file 1914F.go.
  • The implementation visibly relies on sequence storage.
  • 1 loop block 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 1914F — Programming Competition · GoGo
Use this to learn the idea, then write your own version.
package main import (	"bufio"	. "fmt"	"io") // https://space.bilibili.com/206214func cf1914F(_r io.Reader, _w io.Writer) {	in := bufio.NewReader(_r)	out := bufio.NewWriter(_w)	defer out.Flush() 	var T, n, v int	for Fscan(in, &T); T > 0; T-- {		Fscan(in, &n)		g := make([][]int, n)		for w := 1; w < n; w++ {			Fscan(in, &v)			v--			g[v] = append(g[v], w)		} 		size := make([]int, n)		var dfs func(int)		dfs = func(x int) {			size[x] = 1			for i, y := range g[x] {				dfs(y)				size[x] += size[y]				if size[y] > size[g[x][0]] {					g[x][0], g[x][i] = g[x][i], g[x][0]				}			}		}		dfs(0) 		ans := 0		other := 0		x := 0		for {			if other > 0 {				ans++ // 其它点和 v 匹配				other--			}			if len(g[x]) == 0 {				break			} 			s := size[x] - 1			y := g[x][0] 			// 最大子树大小 <= 其它点个数			// 祖先节点已经在上面判断了, other 是不含祖先节点的			if size[y]*2 <= s+other {				ans += (s + other) / 2				break			} 			other += s - size[y]			x = y		}		Fprintln(out, ans)	}} //func main() { cf1914F(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 ↗