- 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
- 64 lines of Go from the credited upstream file 321E.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)7 89func cf321E(in io.Reader, out io.Writer) {10 buf := make([]byte, 4096)11 _i, _n := 0, 012 rc := func() byte {13 if _i == _n {14 _n, _ = in.Read(buf)15 if _n == 0 {16 return 017 }18 _i = 019 }20 b := buf[_i]21 _i++22 return b23 }24 rd := func() (x int) {25 b := rc()26 for ; '0' > b; b = rc() {27 }28 for ; '0' <= b; b = rc() {29 x = x*10 + int(b&15)30 }31 return32 }33 34 n, k := rd(), rd()35 s := make([][]int32, n+1)36 for i := range s {37 s[i] = make([]int32, n+1)38 }39 for i := range n {40 for j := range n {41 s[i+1][j+1] = s[i+1][j] + s[i][j+1] - s[i][j] + int32(rd())42 }43 }44 45 f := make([]int32, n+1)46 opt := make([]int, n+2)47 opt[n+1] = n48 for range k - 1 {49 for i := n; i >= 1; i-- {50 f[i] = -1e951 for j := opt[i]; j <= opt[i+1]; j++ {52 v := f[j] - s[j][j] + s[j][i]53 if v > f[i] {54 f[i] = v55 opt[i] = j56 }57 }58 }59 }60 Fprint(out, s[n][n]/2-f[n])61}62 6364