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.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- 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.
Use this to learn the idea, then write your own version.
1package main2 3import (4 "bufio"5 . "fmt"6 "io"7)8 910func cf1914F(_r io.Reader, _w io.Writer) {11 in := bufio.NewReader(_r)12 out := bufio.NewWriter(_w)13 defer out.Flush()14 15 var T, n, v int16 for Fscan(in, &T); T > 0; T-- {17 Fscan(in, &n)18 g := make([][]int, n)19 for w := 1; w < n; w++ {20 Fscan(in, &v)21 v--22 g[v] = append(g[v], w)23 }24 25 size := make([]int, n)26 var dfs func(int)27 dfs = func(x int) {28 size[x] = 129 for i, y := range g[x] {30 dfs(y)31 size[x] += size[y]32 if size[y] > size[g[x][0]] {33 g[x][0], g[x][i] = g[x][i], g[x][0]34 }35 }36 }37 dfs(0)38 39 ans := 040 other := 041 x := 042 for {43 if other > 0 {44 ans++ 45 other--46 }47 if len(g[x]) == 0 {48 break49 }50 51 s := size[x] - 152 y := g[x][0]53 54 55 56 if size[y]*2 <= s+other {57 ans += (s + other) / 258 break59 }60 61 other += s - size[y]62 x = y63 }64 Fprintln(out, ans)65 }66}67 6869