Approach
Sorting and greedy selection
For Codeforces 311B — Cats Transport, 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
- 62 lines of Go from the credited upstream file 311B.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)8 910type vec11 struct{ x, y int }11 12func (a vec11) sub(b vec11) vec11 { return vec11{a.x - b.x, a.y - b.y} }13func (a vec11) dot(b vec11) int { return a.x*b.x + a.y*b.y }14func (a vec11) det(b vec11) int { return a.x*b.y - a.y*b.x }15 16func cf311B(in io.Reader, out io.Writer) {17 var n, m, p, h, t int18 Fscan(in, &n, &m, &p)19 if p >= m {20 Fprint(out, 0)21 return22 }23 dis := make([]int, n)24 for i := 1; i < n; i++ {25 Fscan(in, &dis[i])26 dis[i] += dis[i-1]27 }28 a := make([]int, m)29 for i := range a {30 Fscan(in, &h, &t)31 a[i] = t - dis[h-1]32 }33 slices.Sort(a)34 s := make([]int, m+1)35 for i, v := range a {36 s[i+1] = s[i] + v37 }38 39 f := make([]int, m+1)40 for i := 1; i <= m; i++ {41 f[i] = 1e1842 }43 for k := 1; k <= p; k++ {44 q := []vec11{{}}45 for i := 1; i <= m; i++ {46 pi := vec11{-a[i-1], 1}47 for len(q) > 1 && pi.dot(q[0]) >= pi.dot(q[1]) {48 q = q[1:]49 }50 v := vec11{i, s[i] + f[i]}51 f[i] = pi.dot(q[0]) + a[i-1]*i - s[i]52 for len(q) > 1 && q[len(q)-1].sub(q[len(q)-2]).det(v.sub(q[len(q)-1])) <= 0 {53 q = q[:len(q)-1]54 }55 q = append(q, v)56 }57 }58 Fprint(out, f[m])59}60 6162