Approach
Depth-first search
For Codeforces 1225F — Tree Factory, 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
- 67 lines of Go from the credited upstream file 1225F.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.
Use this to learn the idea, then write your own version.
1package main2 3import (4 "bufio"5 . "fmt"6 "io"7)8 910func cf1225F(in io.Reader, _w io.Writer) {11 out := bufio.NewWriter(_w)12 defer out.Flush()13 var n int14 Fscan(in, &n)15 pa := make([]int, n)16 g := make([][]int, n)17 dep := make([]int, n)18 for i := 1; i < n; i++ {19 Fscan(in, &pa[i])20 g[pa[i]] = append(g[pa[i]], i)21 dep[i] = dep[pa[i]] + 122 }23 dn := make([]int, n)24 idx := make([]int, n)25 for i := n - 1; i >= 1; i-- {26 if dn[pa[i]] < dn[i]+1 {27 dn[pa[i]] = dn[i] + 128 idx[pa[i]] = i29 }30 }31 32 dfn := make([]int, n)33 tot := 034 var dfs func(int)35 dfs = func(v int) {36 dfn[tot] = v37 tot++38 for _, w := range g[v] {39 if w != idx[v] {40 dfs(w)41 }42 }43 if idx[v] != 0 {44 dfs(idx[v])45 }46 }47 dfs(0)48 49 ans := 050 for i := 1; i < n; i++ {51 ans += dep[dfn[i-1]] - dep[pa[dfn[i]]]52 }53 54 for _, v := range dfn {55 Fprint(out, v, " ")56 }57 Fprintln(out)58 Fprintln(out, ans)59 for i := 1; i < n; i++ {60 for range dep[dfn[i-1]] - dep[pa[dfn[i]]] {61 Fprint(out, dfn[i], " ")62 }63 }64}65 6667