Approach
Depth-first search
For Codeforces 758E — Broken 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
- 89 lines of Go from the credited upstream file 758E.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 cf758E(in io.Reader, _w io.Writer) {11 out := bufio.NewWriter(_w)12 defer out.Flush()13 var n int14 Fscan(in, &n)15 type edge struct{ v, w, wt, p int }16 es := make([]edge, n-1)17 type nb struct{ to, i int }18 g := make([][]nb, n+1)19 for i := range es {20 var v, w, wt, p int21 Fscan(in, &v, &w, &wt, &p)22 es[i] = edge{v, w, wt, p}23 g[v] = append(g[v], nb{w, i})24 }25 26 27 a := make([]struct{ minSum, extraDec int }, n+1)28 var dfs func(int) (int, int)29 dfs = func(v int) (minSum, maxSum int) {30 for _, e := range g[v] {31 w := e.to32 33 mn, mx := dfs(w)34 p := es[e.i].p35 36 if mn < 0 || p < mn {37 return -1, 038 }39 wt := es[e.i].wt40 41 minSum += max(wt-(p-mn), 1) + mn42 43 maxSum += wt + min(mx, p)44 45 46 47 a[w].extraDec = max(mx-p, 0)48 }49 a[v].minSum = minSum50 51 return52 }53 minSum, _ := dfs(1)54 if minSum < 0 {55 Fprint(out, -1)56 return57 }58 59 60 61 62 dec := 063 var modify func(int)64 modify = func(v int) {65 for _, ew := range g[v] {66 w := ew.to67 68 dec += a[w].extraDec69 70 modify(w)71 72 e := &es[ew.i]73 74 d := min(e.wt-1, e.p-a[w].minSum, dec)75 e.wt -= d76 e.p -= d77 dec -= d78 }79 }80 modify(1)81 82 Fprintln(out, n)83 for _, e := range es {84 Fprintln(out, e.v, e.w, e.wt, e.p)85 }86}87 8889