Approach
Depth-first search
For Codeforces 1899G — Unusual Entertainment, 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
- 86 lines of Go from the credited upstream file 1899G.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 9func cf1899G(in io.Reader, _w io.Writer) {10 out := bufio.NewWriter(_w)11 defer out.Flush()12 var T, n, q, l, r, x int13 for Fscan(in, &T); T > 0; T-- {14 Fscan(in, &n, &q)15 g := make([][]int, n)16 for i := 1; i < n; i++ {17 var v, w int18 Fscan(in, &v, &w)19 v--20 w--21 g[v] = append(g[v], w)22 g[w] = append(g[w], v)23 }24 a := make([]int, n)25 for i := range a {26 Fscan(in, &a[i])27 }28 29 nodes := make([]struct{ l, r int }, n)30 dfn := 131 var dfs func(int, int)32 dfs = func(v, fa int) {33 nodes[v].l = dfn34 dfn++35 for _, w := range g[v] {36 if w != fa {37 dfs(w, v)38 }39 }40 nodes[v].r = dfn - 141 }42 dfs(0, -1)43 44 type data struct{ x, d, qid int }45 qs := make([][]data, n)46 for i := 0; i < q; i++ {47 Fscan(in, &l, &r, &x)48 l -= 249 r--50 x--51 if l >= 0 {52 qs[l] = append(qs[l], data{x, -1, i})53 }54 qs[r] = append(qs[r], data{x, 1, i})55 }56 57 ans := make([]int, q)58 t := make([]int, n+1)59 pre := func(i int) (res int) {60 for ; i > 0; i &= i - 1 {61 res += t[i]62 }63 return64 }65 for i, ps := range qs {66 for j := nodes[a[i]-1].l; j <= n; j += j & -j {67 t[j]++68 }69 for _, p := range ps {70 node := nodes[p.x]71 ans[p.qid] += p.d * (pre(node.r) - pre(node.l-1))72 }73 }74 for _, v := range ans {75 if v > 0 {76 Fprintln(out, "YES")77 } else {78 Fprintln(out, "NO")79 }80 }81 Fprintln(out)82 }83}84 8586