- 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 1840F.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 CF1840F(_r io.Reader, _w io.Writer) {11 out := bufio.NewWriter(_w)12 defer out.Flush()13 buf := make([]byte, 1<<12)14 _i := len(buf)15 rc := func() byte {16 if _i >= len(buf) {17 _r.Read(buf)18 _i = 019 }20 b := buf[_i]21 _i++22 return b23 }24 ri := 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 type tuple struct{ x, y, c int }34 dir3 := []tuple{{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}35 36o:37 for T := ri(); T > 0; T-- {38 n, m, r := ri(), ri(), ri()39 type pair struct{ i, t int }40 die := [2]map[pair]bool{{}, {}}41 for i := 0; i < r; i++ {42 t, tp, c := ri(), ri(), ri()43 die[tp-1][pair{c, t}] = true44 }45 vis := make([][][]bool, n+1)46 for i := range vis {47 vis[i] = make([][]bool, m+1)48 for j := range vis[i] {49 vis[i][j] = make([]bool, r+1)50 }51 }52 vis[0][0][0] = true53 q := []tuple{{}}54 for len(q) > 0 {55 p := q[0]56 q = q[1:]57 for _, d := range dir3 {58 x, y, c := p.x+d.x, p.y+d.y, p.c+d.c59 if x <= n && y <= m && c <= r && !vis[x][y][c] && !die[0][pair{x, x + y + c}] && !die[1][pair{y, x + y + c}] {60 if x == n && y == m {61 Fprintln(out, x+y+c)62 continue o63 }64 vis[x][y][c] = true65 q = append(q, tuple{x, y, c})66 }67 }68 }69 Fprintln(out, -1)70 }71}72 7374