Approach
Sorting and greedy selection
For Codeforces 2042D — Recommendations, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 69 lines of Go from the credited upstream file 2042D.go.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
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 "cmp"6 . "fmt"7 "io"8 "slices"9 "sort"10)11 1213type fenwick42 []struct{ maxL, minR int }14 15func (f fenwick42) update(i, l, r int) {16 for ; i < len(f); i += i & -i {17 f[i].maxL = max(f[i].maxL, l)18 f[i].minR = min(f[i].minR, r)19 }20}21 22func (f fenwick42) pre(i int) int {23 maxL, minR := 0, int(2e9)24 for ; i > 0; i &= i - 1 {25 maxL = max(maxL, f[i].maxL)26 minR = min(minR, f[i].minR)27 }28 return minR - maxL29}30 31func cf2042D(in io.Reader, _w io.Writer) {32 out := bufio.NewWriter(_w)33 defer out.Flush()34 var T, n int35 for Fscan(in, &T); T > 0; T-- {36 Fscan(in, &n)37 type tuple struct{ l, r, i int }38 a := make([]tuple, n)39 ls := make([]int, n)40 for i := range a {41 Fscan(in, &a[i].l, &a[i].r)42 a[i].i = i43 ls[i] = a[i].l44 }45 slices.SortFunc(a, func(a, b tuple) int { return cmp.Or(b.r-a.r, a.l-b.l) })46 slices.Sort(ls)47 48 ans := make([]int, n)49 t := make(fenwick42, n+1)50 for i := range t {51 t[i].minR = 2e952 }53 for i, p := range a {54 l := sort.SearchInts(ls, p.l) + 155 if !(i < n-1 && a[i+1].r == p.r && a[i+1].l == p.l) {56 if superSize := t.pre(l); superSize < 2e9 {57 ans[p.i] = superSize - (p.r - p.l)58 }59 }60 t.update(l, p.l, p.r)61 }62 for _, v := range ans {63 Fprintln(out, v)64 }65 }66}67 6869