Use this to learn the idea, then write your own version.
1package main2 3import (4 "bufio"5 . "fmt"6 "io"7 "runtime/debug"8 "sort"9)10 1112 1314func init() { debug.SetGCPercent(-1) }15 16type data84 struct {17 mx, pre, suf int18 full bool19}20type node84 struct {21 lo, ro *node8422 l, r int23 data8424}25 26func max84(a, b int) int {27 if a > b {28 return a29 }30 return b31}32 33func op84(a, b data84) (c data84) {34 c.pre = a.pre35 if a.full {36 c.pre += b.pre37 }38 c.suf = b.suf39 if b.full {40 c.suf += a.suf41 }42 c.mx = max84(max84(max84(a.mx, b.mx), max84(c.pre, c.suf)), a.suf+b.pre)43 c.full = a.full && b.full44 return45}46 47func (o *node84) maintain() {48 o.data84 = op84(o.lo.data84, o.ro.data84)49}50 51func build84(l, r int) *node84 {52 o := &node84{l: l, r: r}53 if l == r {54 return o55 }56 m := (l + r) >> 157 o.lo = build84(l, m)58 o.ro = build84(m+1, r)59 return o60}61 62func (o node84) insert(i int) *node84 {63 if o.l == o.r {64 o.mx, o.pre, o.suf, o.full = 1, 1, 1, true65 return &o66 }67 if m := o.lo.r; i <= m {68 o.lo = o.lo.insert(i)69 } else {70 o.ro = o.ro.insert(i)71 }72 o.maintain()73 return &o74}75 76func (o *node84) query(l, r int) data84 {77 if l <= o.l && o.r <= r {78 return o.data8479 }80 m := o.lo.r81 if r <= m {82 return o.lo.query(l, r)83 }84 if m < l {85 return o.ro.query(l, r)86 }87 return op84(o.lo.query(l, r), o.ro.query(l, r))88}89 90func CF484E(_r io.Reader, _w io.Writer) {91 in := bufio.NewReader(_r)92 out := bufio.NewWriter(_w)93 defer out.Flush()94 95 var n, q, l, r, w int96 Fscan(in, &n)97 type pair struct{ h, i int }98 a := make([]pair, n)99 for i := range a {100 Fscan(in, &a[i].h)101 a[i].i = i102 }103 sort.Slice(a, func(i, j int) bool { return a[i].h > a[j].h })104 105 t := make([]*node84, n+1)106 t[0] = build84(1, n)107 for i, p := range a {108 t[i+1] = t[i].insert(p.i + 1)109 }110 for Fscan(in, &q); q > 0; q-- {111 Fscan(in, &l, &r, &w)112 i := sort.Search(n-1, func(i int) bool { return t[i+1].query(l, r).mx >= w })113 Fprintln(out, a[i].h)114 }115}116 117118