Approach
Depth-first search
For Codeforces 840E — In a Trap, 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
- 81 lines of Go from the credited upstream file 840E.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 cf840E(in io.Reader, _w io.Writer) {11 out := bufio.NewWriter(_w)12 defer out.Flush()13 const B = 25614 var n, q int15 Fscan(in, &n, &q)16 a := make([]int, n+1)17 for i := 1; i <= n; i++ {18 Fscan(in, &a[i])19 }20 21 g := make([][]int, n+1)22 for range n - 1 {23 var u, v int24 Fscan(in, &u, &v)25 g[u] = append(g[u], v)26 g[v] = append(g[v], u)27 }28 29 f := make([][B]int, n+1)30 fa := make([]int, n+1)31 dep := make([]int, n+1)32 jump := make([]int, n+1)33 34 var dfs func(int)35 dfs = func(v int) {36 dep[v] = dep[fa[v]] + 137 for _, w := range g[v] {38 if w != fa[v] {39 fa[w] = v40 dfs(w)41 }42 }43 if dep[v] < B {44 return45 }46 47 u := v48 for i := range B {49 x := (i^a[u])>>8 ^ 25550 f[v][x] = max(f[v][x], 255<<8|(i^a[u]))51 u = fa[u]52 }53 jump[v] = u54 for i := range 8 {55 for j := range B {56 f[v][j] = max(f[v][j], f[v][j^1<<i]-B<<i)57 }58 }59 }60 61 dfs(1)62 63 for range q {64 var u, v int65 Fscan(in, &u, &v)66 d := dep[v] - dep[u] + 167 ans := 068 for i := range d / B {69 ans = max(ans, f[v][i])70 v = jump[v]71 }72 for i := d / B * B; i < d; i++ {73 ans = max(ans, i^a[v])74 v = fa[v]75 }76 Fprintln(out, ans)77 }78}79 8081