- 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
- 116 lines of Go from the credited upstream file 1801B.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 "math/rand"7 "slices"8)9 10type node01 struct {11 lr [2]*node0112 priority int13 key int14}15 16func (o *node01) rotate(d int) *node01 {17 x := o.lr[d^1]18 o.lr[d^1] = x.lr[d]19 x.lr[d] = o20 return x21}22 23type treap01 struct {24 root *node0125}26 27func (t *treap01) _put(o *node01, key int) *node01 {28 if o == nil {29 return &node01{priority: rand.Int(), key: key}30 }31 if d := o.cmp(key); d >= 0 {32 o.lr[d] = t._put(o.lr[d], key)33 if o.lr[d].priority > o.priority {34 o = o.rotate(d ^ 1)35 }36 }37 return o38}39 40func (t *treap01) put(key int) { t.root = t._put(t.root, key) }41 42func (o *node01) cmp(key int) int {43 cur := o.key44 if key == cur {45 return -146 }47 if key < cur {48 return 049 }50 return 151}52 53func (t *treap01) lowerBound(key int) (lb *node01) {54 for o := t.root; o != nil; {55 switch c := o.cmp(key); {56 case c == 0:57 lb = o58 o = o.lr[0]59 case c > 0:60 o = o.lr[1]61 default:62 return o63 }64 }65 return66}67 68func (t *treap01) prev(key int) (prev *node01) {69 for o := t.root; o != nil; {70 if o.cmp(key) <= 0 {71 o = o.lr[0]72 } else {73 prev = o74 o = o.lr[1]75 }76 }77 return78}79 80func cf1801B(in io.Reader, out io.Writer) {81 const inf int = 1e1882 var T, n int83 for Fscan(in, &T); T > 0; T-- {84 Fscan(in, &n)85 type pair struct{ x, y int }86 a := make([]pair, n)87 for i := range a {88 Fscan(in, &a[i].x, &a[i].y)89 }90 slices.SortFunc(a, func(a, b pair) int { return a.x - b.x })91 suf := make([]int, n+1)92 suf[n] = -inf93 for i := n - 1; i > 0; i-- {94 suf[i] = max(suf[i+1], a[i].y)95 }96 97 ans := inf98 t := &treap01{}99 t.put(-inf)100 t.put(inf)101 for i, p := range a {102 x := p.x103 mx := suf[i+1]104 if mx >= x {105 ans = min(ans, mx-x)106 } else {107 ans = min(ans, x-max(t.prev(x).key, mx), t.lowerBound(x).key-x)108 }109 t.put(p.y)110 }111 Fprintln(out, ans)112 }113}114 115116