- 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
- 88 lines of Go from the credited upstream file 1227D2.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 "sort"8)9 10type node1262 struct {11 l, r int12 lo, ro *node126213 sum int14}15type pst1262 []*node126216 17func (t pst1262) _build(l, r int) *node1262 {18 o := &node1262{l: l, r: r}19 if l == r {20 return o21 }22 m := (l + r) >> 123 o.lo = t._build(l, m)24 o.ro = t._build(m+1, r)25 return o26}27 28func (t pst1262) _update(o *node1262, idx int) *node1262 {29 tmp := *o30 o = &tmp31 if o.l == o.r {32 o.sum++33 return o34 }35 if idx <= o.lo.r {36 o.lo = t._update(o.lo, idx)37 } else {38 o.ro = t._update(o.ro, idx)39 }40 o.sum = o.lo.sum + o.ro.sum41 return o42}43 44func (t pst1262) _queryKth(o1, o2 *node1262, k int) (idx int) {45 if o1.l == o1.r {46 return o1.l47 }48 if d := o2.lo.sum - o1.lo.sum; d >= k {49 return t._queryKth(o1.lo, o2.lo, k)50 } else {51 return t._queryKth(o1.ro, o2.ro, k-d)52 }53}54 55func (t pst1262) init(n int) { t[0] = t._build(1, n) }56func (t pst1262) update(ver, idx int) { t[ver+1] = t._update(t[ver], idx) }57func (t pst1262) queryKth(l, r, k int) (idx int) { return t._queryKth(t[l-1], t[r], k) }58 5960func CF1262D2(_r io.Reader, _w io.Writer) {61 in := bufio.NewReader(_r)62 out := bufio.NewWriter(_w)63 defer out.Flush()64 type pair struct{ v, i int }65 66 var n, m, k, p int67 Fscan(in, &n)68 a := make([]int, n)69 ps := make([]pair, n)70 for i := range ps {71 Fscan(in, &a[i])72 ps[i] = pair{a[i], i}73 }74 75 sort.Slice(ps, func(i, j int) bool { a, b := ps[i], ps[j]; return a.v > b.v || a.v == b.v && a.i < b.i })76 t := make(pst1262, n+1)77 t.init(n)78 for i, p := range ps {79 t.update(i, p.i+1)80 }81 for Fscan(in, &m); m > 0; m-- {82 Fscan(in, &k, &p)83 Fprintln(out, a[t.queryKth(1, k, p)-1])84 }85}86 8788