- 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
- 81 lines of Go from the credited upstream file 961E.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 . "fmt"5 "io"6 "runtime/debug"7)8 910func init() { debug.SetGCPercent(-1) }11 12type data61 struct{ cnt int }13type node61 struct {14 lo, ro *node6115 data6116}17 18func (node61) merge(l, r data61) data61 {19 return data61{l.cnt + r.cnt}20}21 22func (o *node61) maintain() {23 o.data61 = o.merge(o.lo.data61, o.ro.data61)24}25 26func build61(l, r int) *node61 {27 o := &node61{}28 if l == r {29 return o30 }31 m := (l + r) >> 132 o.lo = build61(l, m)33 o.ro = build61(m+1, r)34 return o35}36 37func (o node61) update(l, r, i int) *node61 {38 if l == r {39 o.cnt++40 return &o41 }42 m := (l + r) >> 143 if i <= m {44 o.lo = o.lo.update(l, m, i)45 } else {46 o.ro = o.ro.update(m+1, r, i)47 }48 o.maintain()49 return &o50}51 52func (o *node61) query(l, r, ql, qr int) data61 {53 if ql <= l && r <= qr {54 return o.data6155 }56 m := (l + r) >> 157 if qr <= m {58 return o.lo.query(l, m, ql, qr)59 }60 if m < ql {61 return o.ro.query(m+1, r, ql, qr)62 }63 return o.merge(o.lo.query(l, m, ql, qr), o.ro.query(m+1, r, ql, qr))64}65 66func cf961E(in io.Reader, out io.Writer) {67 var n, v, ans int68 Fscan(in, &n)69 t := make([]*node61, n+1)70 t[0] = build61(0, n)71 for i := range n {72 Fscan(in, &v)73 r := min(v, i)74 ans += r - t[r].query(0, n, 0, i).cnt75 t[i+1] = t[i].update(0, n, min(v, n))76 }77 Fprint(out, ans)78}79 8081