- 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
- 53 lines of Go from the credited upstream file 799C.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 . "fmt"5 "io"6 "slices"7)8 910func cf799C(in io.Reader, out io.Writer) {11 var n, c, d, x, p, ans int12 var s string13 Fscan(in, &n, &c, &d)14 type pair struct{ b, p int }15 g := [2][]pair{}16 for range n {17 Fscan(in, &x, &p, &s)18 b := s[0] - 'C'19 g[b] = append(g[b], pair{x, p})20 }21 22 a, b := g[0], g[1]23 maxB := []int{}24 f := func(a []pair, c int) {25 slices.SortFunc(a, func(a, b pair) int { return a.p - b.p })26 preMax := make([]int, len(a)+1)27 preMax[0] = -1e928 mx := int(-1e9)29 j := 030 for i, p := range a {31 d := c - p.p32 if d < 0 {33 break34 }35 preMax[i+1] = max(preMax[i], p.b)36 mx = preMax[i+1]37 if j < i && a[j].p <= d {38 j++39 }40 for j > 0 && a[j-1].p > d {41 j--42 }43 ans = max(ans, p.b+preMax[j])44 }45 maxB = append(maxB, mx)46 }47 f(a, c)48 f(b, d)49 Fprint(out, max(ans, maxB[0]+maxB[1]))50}51 5253