- 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
- 72 lines of Go from the credited upstream file 366C.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)8 910func CF366C(_r io.Reader, out io.Writer) {11 in := bufio.NewReader(_r)12 const mx int = 1e413 max := func(a, b int) int {14 if a > b {15 return a16 }17 return b18 }19 20 var n, k, s int21 Fscan(in, &n, &k)22 a := make([]int, n)23 for i := range a {24 Fscan(in, &a[i])25 }26 b := make([]int, n)27 for i := range b {28 Fscan(in, &b[i])29 if a[i] == k*b[i] {30 s += a[i]31 }32 }33 34 dp1 := make([]int, mx+1)35 for i := range dp1 {36 dp1[i] = -1e937 }38 dp1[0] = 039 for i, v := range a {40 if w := v - k*b[i]; w > 0 {41 for j := mx; j >= w; j-- {42 dp1[j] = max(dp1[j], dp1[j-w]+v)43 }44 }45 }46 dp2 := make([]int, mx+1)47 for i := range dp2 {48 dp2[i] = -1e949 }50 dp2[0] = 051 for i, v := range a {52 if w := k*b[i] - v; w > 0 {53 for j := mx; j >= w; j-- {54 dp2[j] = max(dp2[j], dp2[j-w]+v)55 }56 }57 }58 ans := 059 for i, d := range dp1 {60 if d > 0 && dp2[i] > 0 {61 ans = max(ans, d+dp2[i])62 }63 }64 ans += s65 if ans == 0 {66 ans = -167 }68 Fprint(out, ans)69}70 7172