- 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
- 69 lines of Go from the credited upstream file 1374E1.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 1011func CF1374E1(_r io.Reader, out io.Writer) {12 in := bufio.NewReader(_r)13 min := func(a, b int) int {14 if a > b {15 return b16 }17 return a18 }19 20 var n, k, t, p, q, s int21 g := [4][]int{}22 for Fscan(in, &n, &k); n > 0; n-- {23 Fscan(in, &t, &p, &q)24 x := p<<1 | q25 g[x] = append(g[x], t)26 }27 a, b, both := g[1], g[2], g[3]28 if len(a) > len(b) {29 a, b = b, a30 }31 na, nb := len(a), len(both)32 if na+nb < k {33 Fprint(out, -1)34 return35 }36 37 sort.Ints(a)38 sort.Ints(b)39 if na > k {40 a = a[:k]41 na = k42 }43 for i, v := range b[:na] {44 a[i] += v45 }46 47 sort.Ints(both)48 if nb > k {49 both = both[:k]50 nb = k51 }52 53 for _, v := range both {54 s += v55 }56 for _, v := range a[:k-nb] {57 s += v58 }59 ans := s60 61 for i, v := range a[k-nb:] {62 s += v - both[nb-1-i]63 ans = min(ans, s)64 }65 Fprint(out, ans)66}67 6869