Approach
Depth-first search
For Codeforces 1527D — MEX 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
- 108 lines of Go from the credited upstream file 1527D.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 cf1527D(_r io.Reader, _w io.Writer) {11 in := bufio.NewReader(_r)12 out := bufio.NewWriter(_w)13 defer out.Flush()14 15 var T, n, v, w int16 for Fscan(in, &T); T > 0; T-- {17 Fscan(in, &n)18 g := make([][]int, n)19 for i := 1; i < n; i++ {20 Fscan(in, &v, &w)21 g[v] = append(g[v], w)22 g[w] = append(g[w], v)23 }24 25 ans := make([]int, n+1)26 dfn := make([]int, n)27 size := make([]int, n+1)28 t := 029 var dfs func(int, int) int30 dfs = func(v, fa int) (s int) {31 t++32 dfn[v] = t33 for _, w := range g[v] {34 if w == fa {35 continue36 }37 sz := dfs(w, v)38 if v == 0 {39 ans[0] += sz * (sz - 1) / 2 40 }41 s += sz42 }43 s++44 size[v] = s45 return46 }47 dfs(0, -1)48 isAncestor := func(f, v int) bool { return dfn[f] < dfn[v] && dfn[v] < dfn[f]+size[f] }49 50 p, q, ap := 0, 0, 051 s := 152 for _, w := range g[0] {53 sz := size[w]54 if w == 1 || isAncestor(w, 1) {55 ap = w 56 sz -= size[1] 57 }58 ans[1] += sz * s 59 s += sz60 }61 62 for i := 1; i < n; {63 if q == 0 && isAncestor(p, i) { 64 p = i65 for i++; i < n && isAncestor(i, p); i++ { 66 }67 68 if i == n || isAncestor(p, i) { 69 ans[i] = (n - size[ap]) * (size[p] - size[i])70 } else {71 if i == ap || isAncestor(ap, i) { 72 ans[i] = (n - size[ap]) * size[p]73 break74 }75 76 ans[i] = (n - size[ap] - size[i]) * size[p]77 }78 continue79 }80 if isAncestor(p, i) { 81 p = i82 for i++; i < n && (isAncestor(i, p) || isAncestor(i, q)); i++ { 83 }84 } else { 85 q = i86 for i++; i < n && (isAncestor(i, p) || isAncestor(i, q)); i++ { 87 }88 }89 90 if i < n && isAncestor(p, i) { 91 ans[i] = (size[p] - size[i]) * size[q]92 } else if i < n && isAncestor(q, i) { 93 ans[i] = (size[q] - size[i]) * size[p]94 } else { 95 ans[i] = size[p] * size[q]96 break97 }98 }99 100 for _, v := range ans {101 Fprint(out, v, " ")102 }103 Fprintln(out)104 }105}106 107108