Approach
Depth-first search
For Codeforces 1988D — The Omnipotent Monster Killer, 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
- 63 lines of Go from the credited upstream file 1988D.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 . "fmt"5 "io"6)7 89func cf1988D(in io.Reader, out io.Writer) {10 var T, n int11 for Fscan(in, &T); T > 0; T-- {12 Fscan(in, &n)13 a := make([]int, n)14 s := 015 for i := range a {16 Fscan(in, &a[i])17 s += a[i]18 }19 g := make([][]int, n)20 for range n - 1 {21 var v, w int22 Fscan(in, &v, &w)23 v--24 w--25 g[v] = append(g[v], w)26 g[w] = append(g[w], v)27 }28 var dfs func(int, int) (int, int, int)29 dfs = func(v, fa int) (mn, mn2, mnI int) {30 f := make([]int, min(20, len(g[v])+1))31 for _, w := range g[v] {32 if w == fa {33 continue34 }35 m, m2, i := dfs(w, v)36 for j := range f {37 if j != i {38 f[j] += m39 } else {40 f[j] += m241 }42 }43 }44 mn = int(1e18)45 for i, res := range f {46 res += i * a[v]47 if res < mn {48 mn2 = mn49 mn = res50 mnI = i51 } else if res < mn2 {52 mn2 = res53 }54 }55 return56 }57 mn, _, _ := dfs(0, -1)58 Fprintln(out, s+mn)59 }60}61 6263