- 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
- 65 lines of Go from the credited upstream file 1837F.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 "bufio"5 "container/heap"6 . "fmt"7 "io"8 "sort"9)10 1112func cf1837F(_r io.Reader, _w io.Writer) {13 in := bufio.NewReader(_r)14 out := bufio.NewWriter(_w)15 defer out.Flush()16 17 var T, n, k int18 for Fscan(in, &T); T > 0; T-- {19 Fscan(in, &n, &k)20 a := make([]int, n)21 for i := range a {22 Fscan(in, &a[i])23 }24 suf := make([]int, n+1)25 ans := sort.Search(k*1e9, func(mx int) bool {26 h := hp37{}27 s := mx28 upd := func(v int) {29 if s >= v {30 s -= v31 heap.Push(&h, v)32 } else if h.Len() > 0 && v < h.IntSlice[0] {33 s += h.IntSlice[0] - v34 h.IntSlice[0] = v35 heap.Fix(&h, 0)36 }37 }38 for i := n - 1; i >= 0; i-- {39 upd(a[i])40 if h.Len() >= k {41 return true42 }43 suf[i] = h.Len()44 }45 46 h = hp37{}47 s = mx48 for i, v := range a {49 upd(v)50 if h.Len()+suf[i+1] >= k {51 return true52 }53 }54 return false55 })56 Fprintln(out, ans)57 }58}59 6061type hp37 struct{ sort.IntSlice }62func (h hp37) Less(i, j int) bool { return h.IntSlice[i] > h.IntSlice[j] }63func (h *hp37) Push(v any) { h.IntSlice = append(h.IntSlice, v.(int)) }64func (hp37) Pop() (_ any) { return }65