- 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
- 86 lines of Go from the credited upstream file 1255D.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 "bytes"6 . "fmt"7 "io"8)9 1011func Sol1255D(reader io.Reader, writer io.Writer) {12 in := bufio.NewReader(reader)13 out := bufio.NewWriter(writer)14 defer out.Flush()15 const alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"16 17 var t, r, c, k, lastRi, lastRj, avg, nAvg int18 for Fscan(in, &t); t > 0; t-- {19 Fscan(in, &r, &c, &k)20 cells := make([][]byte, r)21 cnt := 022 for i := range cells {23 Fscan(in, &cells[i])24 if cntRow := bytes.Count(cells[i], []byte{'R'}); cntRow > 0 {25 cnt += cntRow26 lastRi = i27 if i&1 == 0 {28 lastRj = bytes.LastIndex(cells[i], []byte{'R'})29 } else {30 lastRj = bytes.Index(cells[i], []byte{'R'})31 }32 }33 }34 cells[lastRi][lastRj] = '.'35 if r&1 == 1 {36 cells[r-1][c-1] = 'R'37 } else {38 cells[r-1][0] = 'R'39 }40 41 avg = cnt / k42 if cnt%k == 0 {43 nAvg = k44 } else {45 nAvg = (avg+1)*k - cnt46 }47 nowI := 048 nowCnt := 049 left := nAvg50 51 modify := func(i, j int, isRice bool) {52 cells[i][j] = alphabet[nowI]53 if isRice {54 nowCnt++55 if nowCnt == avg {56 nowI++57 nowCnt = 058 left--59 if left == 0 {60 avg++61 left = k - nAvg62 }63 }64 }65 }66 for i, row := range cells {67 if i&1 == 0 {68 for j, ch := range row {69 modify(i, j, ch == 'R')70 }71 } else {72 for j := c - 1; j >= 0; j-- {73 modify(i, j, cells[i][j] == 'R')74 }75 }76 }77 for _, row := range cells {78 Fprintf(out, "%s\n", row)79 }80 }81}82 83848586