Approach
Depth-first search
For Codeforces 87D — Beautiful Road, 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
- 98 lines of Go from the credited upstream file 87D.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 "cmp"6 . "fmt"7 "io"8 "slices"9)10 1112func cf87D(in io.Reader, _w io.Writer) {13 out := bufio.NewWriter(_w)14 defer out.Flush()15 var n int16 Fscan(in, &n)17 type edge struct{ v, w, wt, dep, i int }18 es := make([]edge, n-1)19 g := make([][]int, n)20 for i := range es {21 var v, w, wt int22 Fscan(in, &v, &w, &wt)23 v--24 w--25 es[i] = edge{v, w, wt, 0, i + 1}26 g[v] = append(g[v], w)27 g[w] = append(g[w], v)28 }29 30 dep := make([]int, n)31 var dfs func(int, int)32 dfs = func(v, fa int) {33 for _, w := range g[v] {34 if w != fa {35 dep[w] = dep[v] + 136 dfs(w, v)37 }38 }39 }40 dfs(0, -1)41 42 for i := range es {43 e := &es[i]44 if dep[e.v] > dep[e.w] {45 e.v, e.w = e.w, e.v46 }47 e.dep = dep[e.v]48 }49 slices.SortFunc(es, func(a, b edge) int { return cmp.Or(a.wt-b.wt, b.dep-a.dep) })50 51 fa := make([]int, n)52 sz := make([]int, n)53 for i := range fa {54 fa[i] = i55 sz[i] = 156 }57 find := func(x int) int {58 rt := x59 for fa[rt] != rt {60 rt = fa[rt]61 }62 for fa[x] != rt {63 fa[x], x = rt, fa[x]64 }65 return rt66 }67 68 mx := 069 ans := []int{}70 for i := 0; i < n-1; {71 st := i72 wt := es[st].wt73 for ; i < n-1 && es[i].wt == wt; i++ {74 v, w := es[i].v, es[i].w75 fv := find(v)76 fa[w] = fv77 sz[fv] += sz[w]78 }79 for ; st < i; st++ {80 e := es[st]81 s := sz[e.w] * (sz[find(e.v)] - sz[e.w])82 if s > mx {83 mx = s84 ans = []int{e.i}85 } else if s == mx {86 ans = append(ans, e.i)87 }88 }89 }90 Fprintln(out, mx*2, len(ans))91 slices.Sort(ans)92 for _, v := range ans {93 Fprint(out, v, " ")94 }95}96 9798