Approach
Sorting and greedy selection
For Codeforces 797F — Mice and Holes, 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
- 61 lines of Go from the credited upstream file 797F.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 . "fmt"5 "io"6 "slices"7 "sort"8)9 10func cf797F(in io.Reader, out io.Writer) {11 abs := func(x int) int {12 if x < 0 {13 return -x14 }15 return x16 }17 var n, m, sumCap int18 Fscan(in, &n, &m)19 a := make([]int, n)20 for i := range a {21 Fscan(in, &a[i])22 }23 slices.Sort(a)24 b := make([]struct{ x, cap int }, m)25 for i := range b {26 Fscan(in, &b[i].x, &b[i].cap)27 sumCap += b[i].cap28 }29 if sumCap < n {30 Fprint(out, -1)31 return32 }33 sort.Slice(b, func(i, j int) bool { return b[i].x < b[j].x })34 35 f := make([]int, n+1)36 for j := 1; j <= n; j++ {37 f[j] = 1e1838 }39 s := make([]int, n+1)40 for _, p := range b {41 for j, x := range a {42 s[j+1] = s[j] + abs(x-p.x)43 }44 type pair struct{ v, i int }45 q := []pair{{}}46 for j := 1; j <= n; j++ {47 for len(q) > 0 && f[j]-s[j] <= q[0].v {48 q = q[:len(q)-1]49 }50 q = append(q, pair{f[j]-s[j], j})51 if q[0].i < j-p.cap {52 q = q[1:]53 }54 f[j] = q[0].v + s[j]55 }56 }57 Fprint(out, f[n])58}59 6061