Approach
Depth-first search
For Codeforces 877E — Danil and a Part-time Job, 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
- 122 lines of Go from the credited upstream file 877E.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 "math/bits"8)9 1011type seg []struct {12 l, r int13 ones int14 flip bool15}16 17func (t seg) maintain(o int) {18 t[o].ones = t[o<<1].ones + t[o<<1|1].ones19}20 21func (t seg) doFlip(O int) {22 o := &t[O]23 o.ones = o.r - o.l + 1 - o.ones24 o.flip = !o.flip25}26 27func (t seg) spread(o int) {28 if t[o].flip {29 t.doFlip(o << 1)30 t.doFlip(o<<1 | 1)31 t[o].flip = false32 }33}34 35func (t seg) build(a []int, o, l, r int) {36 t[o].l, t[o].r = l, r37 if l == r {38 t[o].ones = a[l]39 return40 }41 m := (l + r) >> 142 t.build(a, o<<1, l, m)43 t.build(a, o<<1|1, m+1, r)44 t.maintain(o)45}46 47func (t seg) flip(o, l, r int) {48 if l <= t[o].l && t[o].r <= r {49 t.doFlip(o)50 return51 }52 t.spread(o)53 m := (t[o].l + t[o].r) >> 154 if l <= m {55 t.flip(o<<1, l, r)56 }57 if m < r {58 t.flip(o<<1|1, l, r)59 }60 t.maintain(o)61}62 63func (t seg) onesCount(o, l, r int) int {64 if l <= t[o].l && t[o].r <= r {65 return t[o].ones66 }67 t.spread(o)68 m := (t[o].l + t[o].r) >> 169 if r <= m {70 return t.onesCount(o<<1, l, r)71 }72 if m < l {73 return t.onesCount(o<<1|1, l, r)74 }75 return t.onesCount(o<<1, l, r) + t.onesCount(o<<1|1, l, r)76}77 78func cf877E(in io.Reader, _w io.Writer) {79 out := bufio.NewWriter(_w)80 defer out.Flush()81 var n, p, time, q int82 var op string83 Fscan(in, &n)84 g := make([][]int, n)85 for w := 1; w < n; w++ {86 Fscan(in, &p)87 g[p-1] = append(g[p-1], w)88 }89 a := make([]int, n)90 for i := range a {91 Fscan(in, &a[i])92 }93 94 b := make([]int, n)95 nodes := make([]struct{ l, r int }, n)96 var dfs func(int)97 dfs = func(v int) {98 nodes[v].l = time99 b[time] = a[v]100 time++101 for _, w := range g[v] {102 dfs(w)103 }104 nodes[v].r = time - 1105 }106 dfs(0)107 108 t := make(seg, 2<<bits.Len(uint(n-1)))109 t.build(b, 1, 0, n-1)110 for Fscan(in, &q); q > 0; q-- {111 Fscan(in, &op, &p)112 o := nodes[p-1]113 if op[0] == 'p' {114 t.flip(1, o.l, o.r)115 } else {116 Fprintln(out, t.onesCount(1, o.l, o.r))117 }118 }119}120 121122