- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 75 lines of Go from the credited upstream file 383C.go.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
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 CF383C(_r io.Reader, _w io.Writer) {11 in := bufio.NewReader(_r)12 out := bufio.NewWriter(_w)13 defer out.Flush()14 15 var n, q, v, w, dfn, op, val int16 Fscan(in, &n, &q)17 a := make([]int, n)18 for i := range a {19 Fscan(in, &a[i])20 }21 g := make([][]int, n)22 for i := 1; i < n; i++ {23 Fscan(in, &v, &w)24 v--25 w--26 g[v] = append(g[v], w)27 g[w] = append(g[w], v)28 }29 30 nodes := make([]struct{ sgn, l, r int }, n)31 var f func(int, int, int) int32 f = func(v, fa, sgn int) int {33 nodes[v].sgn = sgn34 dfn++35 nodes[v].l = dfn36 sz := 137 for _, w := range g[v] {38 if w != fa {39 sz += f(w, v, -sgn)40 }41 }42 nodes[v].r = nodes[v].l + sz43 return sz44 }45 f(0, -1, 1)46 47 tree := make([]int, n+1)48 add := func(i, val int) {49 for ; i <= n; i += i & -i {50 tree[i] += val51 }52 }53 pre := func(i int) (res int) {54 for ; i > 0; i &= i - 1 {55 res += tree[i]56 }57 return58 }59 60 for ; q > 0; q-- {61 Fscan(in, &op, &v)62 v--63 o := nodes[v]64 if op == 1 {65 Fscan(in, &val)66 add(o.l, val*o.sgn)67 add(o.r, -val*o.sgn)68 } else {69 Fprintln(out, a[v]+pre(o.l)*o.sgn)70 }71 }72}73 7475