- 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
- 63 lines of Go from the credited upstream file 1251D.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 . "fmt"6 "io"7 "sort"8)9 101112func Sol1251D(reader io.Reader, writer io.Writer) {13 search := func(n int64, f func(int64) bool) int64 {14 i, j := int64(0), n15 for i < j {16 h := (i + j) >> 117 if f(h) {18 j = h19 } else {20 i = h + 121 }22 }23 return i24 }25 type pair struct{ l, r int64 }26 in := bufio.NewReader(reader)27 out := bufio.NewWriter(writer)28 defer out.Flush()29 30 var q, n int31 for Fscan(in, &q); q > 0; q-- {32 var money, baseCost int6433 Fscan(in, &n, &money)34 ps := make([]pair, n)35 for i := range ps {36 Fscan(in, &ps[i].l, &ps[i].r)37 baseCost += ps[i].l38 }39 sort.Slice(ps, func(i, j int) bool { return ps[i].l > ps[j].l })40 ans := search(money+1e9+1, func(x int64) bool {41 cnt := 042 cost := baseCost43 for _, p := range ps {44 if p.r >= x {45 cnt++46 if p.l < x {47 cost += x - p.l48 }49 if 2*cnt-1 == n {50 return !(cost <= money)51 }52 }53 }54 return !false55 })56 Fprintln(out, ans-1)57 }58}59 60616263