- 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
- 99 lines of Go from the credited upstream file 1520G.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 CF1520G(_r io.Reader, out io.Writer) {10 _i, buf := 1<<12, make([]byte, 1<<12)11 rc := func() byte {12 if _i == 1<<12 {13 _r.Read(buf)14 _i = 015 }16 b := buf[_i]17 _i++18 return b19 }20 r := func() (x int) {21 b := rc()22 neg := false23 for ; '0' > b; b = rc() {24 if b == '-' {25 neg = true26 }27 }28 for ; '0' <= b; b = rc() {29 x = x*10 + int(b&15)30 }31 if neg {32 return -x33 }34 return35 }36 min := func(a, b int64) int64 {37 if a < b {38 return a39 }40 return b41 }42 const inf int64 = 1e1843 type pair struct{ x, y int }44 var dir4 = []pair{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}45 46 n, m, w := r(), r(), int64(r())47 a := make([][]int, n)48 dis := make([][]int64, n)49 for i := range a {50 a[i] = make([]int, m)51 for j := range a[i] {52 a[i][j] = r()53 }54 dis[i] = make([]int64, m)55 }56 57 ans := inf58 bfsAll := func(sx, sy int) int64 {59 for i := range dis {60 for j := range dis[i] {61 dis[i][j] = -162 }63 }64 dis[sx][sy] = 065 q := []pair{{sx, sy}}66 for curD := w; len(q) > 0; curD += w {67 tmp := q68 q = nil69 for _, p := range tmp {70 for _, d := range dir4 {71 if x, y := p.x+d.x, p.y+d.y; 0 <= x && x < n && 0 <= y && y < m && a[x][y] >= 0 && dis[x][y] < 0 {72 dis[x][y] = curD73 q = append(q, pair{x, y})74 }75 }76 }77 }78 if sx == 0 && dis[n-1][m-1] > 0 {79 ans = dis[n-1][m-1]80 }81 mi := inf82 for i, r := range a {83 for j, v := range r {84 if v > 0 && dis[i][j] >= 0 {85 mi = min(mi, dis[i][j]+int64(v))86 }87 }88 }89 return mi90 }91 ans = min(ans, bfsAll(0, 0)+bfsAll(n-1, m-1))92 if ans == inf {93 ans = -194 }95 Fprint(out, ans)96}97 9899