Approach
Depth-first search
For Codeforces 740D, 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
- 88 lines of Go from the credited upstream file 740D.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 91011 1213func CF740D(_r io.Reader, _w io.Writer) {14 in := bufio.NewScanner(_r)15 in.Split(bufio.ScanWords)16 out := bufio.NewWriter(_w)17 defer out.Flush()18 read := func() (x int) {19 in.Scan()20 for _, b := range in.Bytes() {21 x = x*10 + int(b-'0')22 }23 return24 }25 type edge struct{ to, l int }26 27 n := read()28 a := make([]int64, n)29 for i := range a {30 a[i] = int64(read())31 }32 const mx = 1933 pa := make([][mx]int, n)34 pa[0][0] = -135 g := make([][]edge, n)36 for w := 1; w < n; w++ {37 v := read() - 138 g[v] = append(g[v], edge{w, read()})39 pa[w][0] = v40 }41 for k := 0; k+1 < mx; k++ {42 for v := range pa {43 if p := pa[v][k]; p != -1 {44 pa[v][k+1] = pa[p][k]45 } else {46 pa[v][k+1] = -147 }48 }49 }50 51 dep := make([]int64, n)52 var f func(int, int64)53 f = func(v int, d int64) {54 dep[v] = d55 for _, e := range g[v] {56 f(e.to, d+int64(e.l))57 }58 }59 f(0, 0)60 61 diff := make([]int, n)62 for v, val := range a {63 u := v64 dv := dep[v]65 for i := mx - 1; i >= 0; i-- {66 if p := pa[u][i]; p != -1 && dv-dep[p] <= val {67 u = p68 }69 }70 diff[v]++71 diff[u]--72 }73 74 ans := make([]interface{}, n)75 var f2 func(int) int76 f2 = func(v int) (sum int) {77 for _, e := range g[v] {78 sum += f2(e.to)79 }80 ans[v] = sum81 return sum + diff[v]82 }83 f2(0)84 Fprint(out, ans...)85}86 8788