- 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 754D.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 CF754D(_r io.Reader, _w io.Writer) {13 in := bufio.NewReader(_r)14 out := bufio.NewWriter(_w)15 defer out.Flush()16 17 var n, k, ans, l int18 Fscan(in, &n, &k)19 a := make([]struct{ l, r, i int }, n)20 for i := range a {21 Fscan(in, &a[i].l, &a[i].r)22 a[i].i = i23 }24 25 sort.Slice(a, func(i, j int) bool { return a[i].l < a[j].l })26 h := hp54{make([]int, k)}27 for i, p := range a[:k] {28 h.IntSlice[i] = p.r29 }30 heap.Init(&h)31 d := h.IntSlice[0] - a[k-1].l + 132 if d > ans {33 ans = d34 l = a[k-1].l35 }36 for _, p := range a[k:] {37 if p.r > h.IntSlice[0] {38 h.IntSlice[0] = p.r39 heap.Fix(&h, 0)40 d := h.IntSlice[0] - p.l + 141 if d > ans {42 ans = d43 l = p.l44 }45 }46 }47 48 Fprintln(out, ans)49 for _, p := range a {50 if ans == 0 || p.l <= l && p.r >= l+ans-1 {51 Fprint(out, p.i+1, " ")52 if k--; k == 0 {53 break54 }55 }56 }57}58 5960 61type hp54 struct{ sort.IntSlice }62 63func (hp54) Push(interface{}) {}64func (hp54) Pop() (_ interface{}) { return }65