Approach
Depth-first search
For Codeforces 2040D — Non Prime 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
- 62 lines of Go from the credited upstream file 2040D.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 cf2040D(in io.Reader, _w io.Writer) {11 out := bufio.NewWriter(_w)12 defer out.Flush()13 const mx int = 4e5 + 114 np := [mx]bool{1: true}15 for i := 2; i*i < mx; i++ {16 if !np[i] {17 for j := i * i; j < mx; j += i {18 np[j] = true19 }20 }21 }22 23 var T, n int24 for Fscan(in, &T); T > 0; T-- {25 Fscan(in, &n)26 g := make([][]int, n)27 for range n - 1 {28 var v, w int29 Fscan(in, &v, &w)30 v--31 w--32 g[v] = append(g[v], w)33 g[w] = append(g[w], v)34 }35 36 ans := make([]int, n)37 ans[0] = 138 cur := 239 var dfs func(int, int)40 dfs = func(v, fa int) {41 for _, w := range g[v] {42 if w == fa {43 continue44 }45 for !np[cur-ans[v]] {46 cur++47 }48 ans[w] = cur49 cur++50 dfs(w, v)51 }52 }53 dfs(0, -1)54 for _, v := range ans {55 Fprint(out, v, " ")56 }57 Fprintln(out)58 }59}60 6162