Approach
Depth-first search
For Codeforces 2118D2 — Red Light, Green Light (Hard version), 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
- 76 lines of Go from the credited upstream file 2118D2.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 "sort"8)9 1011func cf2118D2(in io.Reader, _w io.Writer) {12 out := bufio.NewWriter(_w)13 defer out.Flush()14 var T, n, k, q, v int15 for Fscan(in, &T); T > 0; T-- {16 Fscan(in, &n, &k)17 x := make([]int, n)18 for i := range x {19 Fscan(in, &x[i])20 }21 d := make([]int, n)22 to := make([]int, n*2)23 for i := range to {24 to[i] = -125 }26 idx := map[int][]int{}27 last := map[int]int{}28 for i := range d {29 Fscan(in, &d[i])30 v := (x[i]%k - d[i] + k) % k31 if j, ok := last[v]; ok {32 to[n+j] = i33 }34 last[v] = i35 idx[v] = append(idx[v], i)36 }37 38 last = map[int]int{}39 for i := n - 1; i >= 0; i-- {40 v := (x[i] + d[i]) % k41 if j, ok := last[v]; ok {42 to[j] = n + i43 }44 last[v] = i45 }46 47 vis := make([]int8, n*2)48 var dfs func(int) bool49 dfs = func(v int) bool {50 if vis[v] != 0 {51 return vis[v] > 052 }53 vis[v] = -154 if w := to[v]; w < 0 || dfs(w) {55 vis[v] = 156 return true57 }58 return false59 }60 61 Fscan(in, &q)62 for range q {63 Fscan(in, &v)64 id := idx[v%k]65 i := sort.Search(len(id), func(i int) bool { return x[id[i]] >= v })66 if i == len(id) || dfs(id[i]) {67 Fprintln(out, "YES")68 } else {69 Fprintln(out, "NO")70 }71 }72 }73}74 7576