Approach
Depth-first search
For Codeforces 543D — Road Improvement, 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
- 83 lines of Go from the credited upstream file 543D.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 CF543D(_r io.Reader, _w io.Writer) {11 in := bufio.NewReader(_r)12 out := bufio.NewWriter(_w)13 defer out.Flush()14 const mod = 1_000_000_00715 pow := func(x int64, n int) (res int64) {16 res = 117 for ; n > 0; n /= 2 {18 if n%2 > 0 {19 res = res * x % mod20 }21 x = x * x % mod22 }23 return24 }25 26 var n, v int27 Fscan(in, &n)28 g := make([][]int, n)29 for w := 1; w < n; w++ {30 Fscan(in, &v)31 g[v-1] = append(g[v-1], w)32 }33 34 type pair struct {35 k int36 x int6437 }38 add1 := func(p pair) pair {39 if p.k > 0 {40 return pair{0, 1}41 }42 if p.x == mod-1 {43 return pair{1, 1}44 }45 return pair{0, p.x + 1}46 }47 mul := func(p, q pair) pair { return pair{p.k + q.k, p.x * q.x % mod} }48 div := func(p, q pair) pair { return pair{p.k - q.k, p.x * pow(q.x, mod-2) % mod} }49 50 f := make([]pair, n)51 var dfs func(int)52 dfs = func(v int) {53 f[v].x = 154 for _, w := range g[v] {55 dfs(w)56 f[v] = mul(f[v], add1(f[w]))57 }58 }59 dfs(0)60 61 ans := make([]pair, n)62 ans[0] = f[0]63 var reroot func(int)64 reroot = func(v int) {65 for _, w := range g[v] {66 fp := div(ans[v], add1(f[w]))67 ans[w] = mul(f[w], add1(fp))68 reroot(w)69 }70 }71 reroot(0)72 73 for _, p := range ans {74 if p.k > 0 {75 Fprint(out, "0 ")76 } else {77 Fprint(out, p.x, " ")78 }79 }80}81 8283