Problem solution · Go

Codeforces 1988D — The Omnipotent Monster Killer

Codeforces 1988D — The Omnipotent Monster Killer: a Go solution using depth-first search. Learn the idea, check the complexity, and read the full code, with credit to EndlessCheng Codeforces Go.

Technique
Depth-first search
Source
EndlessCheng Codeforces Go
Length
63 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

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.

  1. Define the state carried into one recursive or stack frame.
  2. Mark or choose the current state before exploring children.
  3. 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.

Source

Code and credit

This code comes from EndlessCheng Codeforces Go by Σndless (EndlessCheng) and is used under the MIT licence.

Full codeCodeforces 1988D — The Omnipotent Monster Killer · GoGo
Use this to learn the idea, then write your own version.
package main import (	. "fmt"	"io") // https://github.com/EndlessChengfunc cf1988D(in io.Reader, out io.Writer) {	var T, n int	for Fscan(in, &T); T > 0; T-- {		Fscan(in, &n)		a := make([]int, n)		s := 0		for i := range a {			Fscan(in, &a[i])			s += a[i]		}		g := make([][]int, n)		for range n - 1 {			var v, w int			Fscan(in, &v, &w)			v--			w--			g[v] = append(g[v], w)			g[w] = append(g[w], v)		}		var dfs func(int, int) (int, int, int)		dfs = func(v, fa int) (mn, mn2, mnI int) {			f := make([]int, min(20, len(g[v])+1))			for _, w := range g[v] {				if w == fa {					continue				}				m, m2, i := dfs(w, v)				for j := range f {					if j != i {						f[j] += m					} else {						f[j] += m2					}				}			}			mn = int(1e18)			for i, res := range f {				res += i * a[v]				if res < mn {					mn2 = mn					mn = res					mnI = i				} else if res < mn2 {					mn2 = res				}			}			return		}		mn, _, _ := dfs(0, -1)		Fprintln(out, s+mn)	}} //func main() { cf1988D(bufio.NewReader(os.Stdin), os.Stdout) } 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗