Use this to learn the idea, then write your own version.
1package main2 3import (4 . "fmt"5 "io"6 "math/bits"7 "slices"8 "sort"9)10 1112type pair struct{ mx, i int }13type seg []struct{ pair; l, r, todo int }14 15func (t seg) merge(a, b pair) pair {16 if a.mx > b.mx {17 return a18 }19 return b20}21 22func (t seg) apply(o, f int) {23 t[o].mx += f24 t[o].todo += f25}26 27func (t seg) maintain(o int) {28 t[o].pair = t.merge(t[o<<1].pair, t[o<<1|1].pair)29}30 31func (t seg) spread(o int) {32 f := t[o].todo33 if f == 0 {34 return35 }36 t.apply(o<<1, f)37 t.apply(o<<1|1, f)38 t[o].todo = 039}40 41func (t seg) build(a []int, o, l, r int) {42 t[o].l, t[o].r = l, r43 if l == r {44 t[o].mx = a[l]45 t[o].i = l46 return47 }48 m := (l + r) >> 149 t.build(a, o<<1, l, m)50 t.build(a, o<<1|1, m+1, r)51 t.maintain(o)52}53 54func (t seg) update(o, l, r, f int) {55 if l <= t[o].l && t[o].r <= r {56 t.apply(o, f)57 return58 }59 t.spread(o)60 m := (t[o].l + t[o].r) >> 161 if l <= m {62 t.update(o<<1, l, r, f)63 }64 if m < r {65 t.update(o<<1|1, l, r, f)66 }67 t.maintain(o)68}69 70func (t seg) query(o, l, r int) pair {71 if l <= t[o].l && t[o].r <= r {72 return t[o].pair73 }74 t.spread(o)75 m := (t[o].l + t[o].r) >> 176 if r <= m {77 return t.query(o<<1, l, r)78 }79 if l > m {80 return t.query(o<<1|1, l, r)81 }82 return t.merge(t.query(o<<1, l, r), t.query(o<<1|1, l, r))83}84 85func cf1221F(in io.Reader, out io.Writer) {86 var n, ans int87 Fscan(in, &n)88 89 90 91 92 93 94 95 96 97 98 type point struct{ x, y, c int }99 a := make([]point, n)100 b := make([]int, 0, n*2)101 for i := range a {102 Fscan(in, &a[i].x, &a[i].y, &a[i].c)103 if a[i].x > a[i].y {104 a[i].x, a[i].y = a[i].y, a[i].x105 }106 b = append(b, a[i].x, a[i].y)107 }108 slices.Sort(b)109 b = slices.Compact(b)110 m := len(b)111 112 t := make(seg, 2<<bits.Len(uint(m-1)))113 t.build(b, 1, 0, m-1)114 115 slices.SortFunc(a, func(a, b point) int { return a.y - b.y })116 x1, x2 := int(2e9), int(2e9)117 for i := 0; i < n; {118 y := a[i].y119 for ; i < n && a[i].y == y; i++ {120 t.update(1, 0, sort.SearchInts(b, a[i].x), a[i].c)121 }122 res := t.query(1, 0, sort.SearchInts(b, y))123 if res.mx-y > ans {124 ans, x1, x2 = res.mx-y, b[res.i], y125 }126 }127 Fprintln(out, ans)128 Fprint(out, x1, x1, x2, x2)129}130 131132