- 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
- 149 lines of Go from the credited upstream file 387E.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 "time"8)9 1011func init() { debug.SetGCPercent(-1) }12 13type node87 struct {14 lr [2]*node8715 priority uint16 key int17}18 19func (o *node87) cmp(b int) int {20 switch {21 case b < o.key:22 return 023 case b > o.key:24 return 125 default:26 return -127 }28}29 30func (o *node87) rotate(d int) *node87 {31 x := o.lr[d^1]32 o.lr[d^1] = x.lr[d]33 x.lr[d] = o34 return x35}36 37type treap87 struct {38 rd uint39 root *node8740}41 42func (t *treap87) fastRand() uint {43 t.rd ^= t.rd << 1344 t.rd ^= t.rd >> 1745 t.rd ^= t.rd << 546 return t.rd47}48 49func (t *treap87) _put(o *node87, key int) *node87 {50 if o == nil {51 return &node87{priority: t.fastRand(), key: key}52 }53 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 }59 return o60}61 62func (t *treap87) put(key int) { t.root = t._put(t.root, key) }63 64func (t *treap87) prev(key int) (prev *node87) {65 for o := t.root; o != nil; {66 if o.cmp(key) <= 0 {67 o = o.lr[0]68 } else {69 prev = o70 o = o.lr[1]71 }72 }73 return74}75 76func (t *treap87) next(key int) (next *node87) {77 for o := t.root; o != nil; {78 if o.cmp(key) == 0 {79 next = o80 o = o.lr[0]81 } else {82 o = o.lr[1]83 }84 }85 return86}87 88func CF387E(_r io.Reader, out io.Writer) {89 _i, buf := 1<<12, make([]byte, 1<<12)90 rc := func() byte {91 if _i == 1<<12 {92 _r.Read(buf)93 _i = 094 }95 b := buf[_i]96 _i++97 return b98 }99 r := func() (x int) {100 b := rc()101 for ; '0' > b; b = rc() {102 }103 for ; '0' <= b; b = rc() {104 x = x*10 + int(b&15)105 }106 return107 }108 109 n, m := r(), r()110 pos := make([]int, n+1)111 for i := 1; i <= n; i++ {112 pos[r()] = i113 }114 save := make([]bool, n+1)115 for ; m > 0; m-- {116 save[r()] = true117 }118 tree := make([]int, n+1)119 add := func(i int) {120 for ; i <= n; i += i & -i {121 tree[i]++122 }123 }124 sum := func(i int) (s int) {125 for ; i > 0; i &= i - 1 {126 s += tree[i]127 }128 return129 }130 131 ans := int64(0)132 t := &treap87{rd: uint(time.Now().UnixNano())/2 + 1}133 t.put(0)134 t.put(n + 1)135 for i := 1; i <= n; i++ {136 p := pos[i]137 if save[i] {138 t.put(p)139 } else {140 l, r := t.prev(p).key, t.next(p).key-1141 ans += int64(r - l - sum(r) + sum(l))142 add(p)143 }144 }145 Fprint(out, ans)146}147 148149