Approach
Depth-first search
For Codeforces 1328E — Tree Queries, 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
- 93 lines of Go from the credited upstream file 1328E.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 CF1328E(_r io.Reader, _w io.Writer) {11 in := bufio.NewReader(_r)12 out := bufio.NewWriter(_w)13 defer out.Flush()14 15 var n, q, v, w, k int16 Fscan(in, &n, &q)17 g := make([][]int, n)18 for i := 1; i < n; i++ {19 Fscan(in, &v, &w)20 v--21 w--22 g[v] = append(g[v], w)23 g[w] = append(g[w], v)24 }25 26 const mx = 1927 pa := make([][mx]int, n)28 dep := make([]int, n)29 var dfs func(v, p, d int)30 dfs = func(v, p, d int) {31 pa[v][0] = p32 dep[v] = d33 for _, w := range g[v] {34 if w != p {35 dfs(w, v, d+1)36 }37 }38 }39 dfs(0, -1, 0)40 for k := 0; k+1 < mx; k++ {41 for v := range pa {42 if p := pa[v][k]; p != -1 {43 pa[v][k+1] = pa[p][k]44 } else {45 pa[v][k+1] = -146 }47 }48 }49 _lca := func(v, w int) int {50 if dep[v] > dep[w] {51 v, w = w, v52 }53 for k := 0; k < mx; k++ {54 if (dep[w]-dep[v])>>k&1 == 1 {55 w = pa[w][k]56 }57 }58 if v == w {59 return v60 }61 for k := mx - 1; k >= 0; k-- {62 if pa[v][k] != pa[w][k] {63 v, w = pa[v][k], pa[w][k]64 }65 }66 return pa[v][0]67 }68 69o:70 for ; q > 0; q-- {71 Fscan(in, &k)72 vs := make([]int, k)73 maxDep, maxV := 0, 074 for i := range vs {75 Fscan(in, &v)76 v--77 if dep[v] > maxDep {78 maxDep, maxV = dep[v], v79 }80 vs[i] = v81 }82 for _, v := range vs {83 if dep[v]-dep[_lca(maxV, v)] > 1 {84 Fprintln(out, "NO")85 continue o86 }87 }88 Fprintln(out, "YES")89 }90}91 9293