Use this to learn the idea, then write your own version.
1package main2 3import (4 "bufio"5 . "fmt"6 "io"7 "sort"8)9 1011 12type pair1321 struct{ val, cost int }13type node1321 struct{ l, r, max, todo int }14type seg1321 []node132115 16func (seg1321) max(a, b int) int {17 if a > b {18 return a19 }20 return b21}22 23func (t seg1321) _pushUp(o int) { t[o].max = t.max(t[o<<1].max, t[o<<1|1].max) }24 25func (t seg1321) _build(a []pair1321, o, l, r int) {26 t[o].l, t[o].r = l, r27 if l == r {28 t[o].max = -a[l-1].cost29 return30 }31 m := (l + r) >> 132 t._build(a, o<<1, l, m)33 t._build(a, o<<1|1, m+1, r)34 t._pushUp(o)35}36 37func (t seg1321) _spread(o int) {38 if add := t[o].todo; add != 0 {39 lo, ro := &t[o<<1], &t[o<<1|1]40 lo.max += add41 ro.max += add42 lo.todo += add43 ro.todo += add44 t[o].todo = 045 }46}47 48func (t seg1321) _update(o, l, r, add int) {49 ol, or := t[o].l, t[o].r50 if l <= ol && or <= r {51 t[o].max += add52 t[o].todo += add53 return54 }55 t._spread(o)56 m := (ol + or) >> 157 if l <= m {58 t._update(o<<1, l, r, add)59 }60 if m < r {61 t._update(o<<1|1, l, r, add)62 }63 t._pushUp(o)64}65 66func (t seg1321) init(a []pair1321) { t._build(a, 1, 1, len(a)) }67func (t seg1321) update(l, r, val int) { t._update(1, l, r, val) }68func (t seg1321) maxAll() int { return t[1].max }69 70func CF1321E(_r io.Reader, _w io.Writer) {71 in := bufio.NewScanner(_r)72 in.Split(bufio.ScanWords)73 read := func() (x int) {74 in.Scan()75 for _, b := range in.Bytes() {76 x = x*10 + int(b-'0')77 }78 return79 }80 81 n, m, p := read(), read(), read()82 a := make([]pair1321, n)83 for i := range a {84 a[i] = pair1321{read(), read()}85 }86 sort.Slice(a, func(i, j int) bool { return a[i].val < a[j].val })87 b := make([]pair1321, m)88 for i := range b {89 b[i] = pair1321{read(), read()}90 }91 sort.Slice(b, func(i, j int) bool { return b[i].val < b[j].val })92 t := make(seg1321, 4*m)93 t.init(b)94 type monster struct{ x, y, coins int }95 monsters := make([]monster, p)96 for i := range monsters {97 monsters[i] = monster{read(), read(), read()}98 }99 sort.Slice(monsters, func(i, j int) bool { return monsters[i].x < monsters[j].x })100 101 ans := int(-2e9)102 i := 0103 for _, weapon := range a {104 for ; i < p; i++ {105 mst := monsters[i]106 if mst.x >= weapon.val {107 break108 }109 if minArmourI := sort.Search(m, func(i int) bool { return b[i].val > mst.y }); minArmourI < m {110 t.update(minArmourI+1, m, mst.coins)111 }112 }113 if profit := t.maxAll() - weapon.cost; profit > ans {114 ans = profit115 }116 }117 Fprint(_w, ans)118}119 120121