Approach
Depth-first search
For Codeforces 2112D — Reachability and Tree, 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
- 57 lines of Go from the credited upstream file 2112D.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 cf2112D(in io.Reader, _w io.Writer) {11 out := bufio.NewWriter(_w)12 defer out.Flush()13 var T, n int14 for Fscan(in, &T); T > 0; T-- {15 Fscan(in, &n)16 g := make([][]int, n+1)17 for range n - 1 {18 var v, w int19 Fscan(in, &v, &w)20 g[v] = append(g[v], w)21 g[w] = append(g[w], v)22 }23 24 rt := 025 for i, es := range g {26 if len(es) == 2 {27 rt = i28 break29 }30 }31 if rt == 0 {32 Fprintln(out, "NO")33 continue34 }35 36 Fprintln(out, "YES")37 var dfs func(int, int, bool)38 dfs = func(v, fa int, rev bool) {39 for _, w := range g[v] {40 if w == fa {41 continue42 }43 if rev {44 Fprintln(out, w, v)45 } else {46 Fprintln(out, v, w)47 }48 dfs(w, v, !rev)49 }50 }51 dfs(rt, g[rt][1], false)52 dfs(rt, g[rt][0], true)53 }54}55 5657