Problem solution · Go

Codeforces 68D — Half-decay tree

Codeforces 68D — Half-decay tree: 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
43 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 68D — Half-decay tree, 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

  • 43 lines of Go from the credited upstream file 68D.go.
  • The implementation keeps its working state in language-native values and containers.
  • 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 68D — Half-decay tree · GoGo
Use this to learn the idea, then write your own version.
package main import (	"bufio"	. "fmt"	"io") // https://github.com/EndlessChengfunc cf68D(in io.Reader, _w io.Writer) {	out := bufio.NewWriter(_w)	defer out.Flush()	a := map[int]int{}	subSum := map[int]int{}	var dfs func(int, int) float64	dfs = func(o, maxFaS int) float64 {		if subSum[o] <= maxFaS { // 最优性剪枝			return float64(maxFaS)		}		lv := dfs(o*2, max(maxFaS, a[o]+subSum[o*2+1])) // 当前节点 + 右子树		rv := dfs(o*2+1, max(maxFaS, a[o]+subSum[o*2])) // 当前节点 + 左子树		return (lv + rv) / 2	} 	var q, v, e int	var op string	Fscan(in, &q, &q)	for range q {		Fscan(in, &op)		if op[0] == 'd' {			Fprintf(out, "%.4f\n", dfs(1, 0))			continue		}		Fscan(in, &v, &e)		a[v] += e		for ; v > 0; v /= 2 {			subSum[v] += e		}	}} //func main() { cf68D(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 ↗