- 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
- 74 lines of Go from the credited upstream file 1551D2.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 CF1551D2(_r io.Reader, _w io.Writer) {11 in := bufio.NewReader(_r)12 out := bufio.NewWriter(_w)13 defer out.Flush()14 15 var T, n, m, k int16 for Fscan(in, &T); T > 0; T-- {17 Fscan(in, &n, &m, &k)18 ans := make([][]byte, n)19 for i := range ans {20 ans[i] = make([]byte, m)21 }22 if n&1 > 0 {23 k -= m / 224 if k < 0 {25 Fprintln(out, "NO")26 continue27 }28 for j := 1; j < m; j += 2 {29 c := 'f' ^ byte(j/2&1)30 ans[n-1][j-1] = c31 ans[n-1][j] = c32 }33 } else if m&1 > 0 {34 if k > m/2*n {35 Fprintln(out, "NO")36 continue37 }38 for i := 1; i < n; i += 2 {39 c := 'f' ^ byte(i/2&1)40 ans[i-1][m-1] = c41 ans[i][m-1] = c42 }43 }44 if k&1 > 0 {45 Fprintln(out, "NO")46 continue47 }48 for i := 1; i < n; i += 2 {49 for j := 1; j < m; j += 2 {50 if k > 0 {51 k -= 252 c := 'b' ^ byte(j/2&1)53 ans[i-1][j-1] = c54 ans[i-1][j] = c55 ans[i][j-1] = c ^ 156 ans[i][j] = c ^ 157 } else {58 c := 'd' ^ byte(i/2&1)59 ans[i-1][j-1] = c60 ans[i-1][j] = c ^ 161 ans[i][j-1] = c62 ans[i][j] = c ^ 163 }64 }65 }66 Fprintln(out, "YES")67 for _, r := range ans {68 Fprintf(out, "%s\n", r)69 }70 }71}72 7374