- 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
- 110 lines of Go from the credited upstream file 1042D.go.
- The implementation keeps its working state in language-native values and containers.
- 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 910type node42 struct {11 lr [2]*node4212 priority uint13 key int14 keyCnt int15 subCnt int16}17 18func (o *node42) size() int {19 if o != nil {20 return o.subCnt21 }22 return 023}24 25func (o *node42) maintain() {26 o.subCnt = o.keyCnt + o.lr[0].size() + o.lr[1].size()27}28 29func (o *node42) rotate(d int) *node42 {30 x := o.lr[d^1]31 o.lr[d^1] = x.lr[d]32 x.lr[d] = o33 o.maintain()34 x.maintain()35 return x36}37 38type treap42 struct {39 rd uint40 root *node4241}42 43func (t *treap42) fastRand() uint {44 t.rd ^= t.rd << 1345 t.rd ^= t.rd >> 1746 t.rd ^= t.rd << 547 return t.rd48}49 50func (t *treap42) _put(o *node42, key int) *node42 {51 if o == nil {52 o = &node42{priority: t.fastRand(), key: key, keyCnt: 1}53 } else if d := o.cmp(key); d >= 0 {54 o.lr[d] = t._put(o.lr[d], key)55 if o.lr[d].priority > o.priority {56 o = o.rotate(d ^ 1)57 }58 } else {59 o.keyCnt++60 }61 o.maintain()62 return o63}64 65func (t *treap42) put(key int) { t.root = t._put(t.root, key) }66 67func (o *node42) cmp(a int) int {68 b := o.key69 if a == b {70 return -171 }72 if a > b {73 return 074 }75 return 176}77 78func (t *treap42) gr(key int) (cnt int) {79 for o := t.root; o != nil; {80 switch c := o.cmp(key); {81 case c == 0:82 o = o.lr[0]83 case c > 0:84 cnt += o.lr[0].size() + o.keyCnt85 o = o.lr[1]86 default:87 cnt += o.lr[0].size()88 return89 }90 }91 return92}93 94func cf1042D(_r io.Reader, out io.Writer) {95 in := bufio.NewReader(_r)96 var n, upper, v, s, ans int97 Fscan(in, &n, &upper)98 t := &treap42{rd: 1}99 t.put(0)100 for ; n > 0; n-- {101 Fscan(in, &v)102 s += v103 ans += t.gr(s - upper)104 t.put(s)105 }106 Fprint(out, ans)107}108 109110