- 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
- 83 lines of Go from the credited upstream file 840D.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 910 1112type node40 struct {13 lo, ro *node4014 cnt int15}16 17func build40(l, r int) *node40 {18 o := &node40{}19 if l == r {20 return o21 }22 m := (l + r) >> 123 o.lo = build40(l, m)24 o.ro = build40(m+1, r)25 return o26}27 28func (o node40) update(l, r, i int) *node40 {29 if l == r {30 o.cnt++31 return &o32 }33 m := (l + r) >> 134 if i <= m {35 o.lo = o.lo.update(l, m, i)36 } else {37 o.ro = o.ro.update(m+1, r, i)38 }39 o.cnt = o.lo.cnt + o.ro.cnt40 return &o41}42 43func (o *node40) query(old *node40, l, r, k int) (int, int) {44 if l == r {45 return o.cnt - old.cnt, l46 }47 m := (l + r) >> 148 cntL := o.lo.cnt - old.lo.cnt49 if k <= cntL {50 return o.lo.query(old.lo, l, m, k)51 }52 return o.ro.query(old.ro, m+1, r, k-cntL)53}54 55func cf840D(in io.Reader, _w io.Writer) {56 out := bufio.NewWriter(_w)57 defer out.Flush()58 var n, q, v, l, r, k int59 Fscan(in, &n, &q)60 t := make([]*node40, n+1)61 t[0] = build40(1, n)62 for i := range n {63 Fscan(in, &v)64 t[i+1] = t[i].update(1, n, v)65 }66o:67 for range q {68 Fscan(in, &l, &r, &k)69 l--70 d := (r-l)/k + 171 for k := d; k <= r-l; k += d {72 cnt, v := t[r].query(t[l], 1, n, k)73 if cnt >= d {74 Fprintln(out, v)75 continue o76 }77 }78 Fprintln(out, -1)79 }80}81 8283