- 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
- 87 lines of Go from the credited upstream file 1301F.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 "slices"8)9 1011func cf1301F(in io.Reader, _w io.Writer) {12 out := bufio.NewWriter(_w)13 defer out.Flush()14 type pair struct{ x, y int16 }15 dir4 := []pair{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}16 abs := func(x int) int {17 if x < 0 {18 return -x19 }20 return x21 }22 23 var n, m, k int1624 Fscan(in, &n, &m, &k)25 a := make([][]int8, n)26 g := make([][]pair, k)27 for i := range a {28 a[i] = make([]int8, m)29 for j := range a[i] {30 Fscan(in, &a[i][j])31 a[i][j]--32 g[a[i][j]] = append(g[a[i][j]], pair{int16(i), int16(j)})33 }34 }35 36 dis := make([][][]int8, k)37 for st := range dis {38 d := make([][]int8, n)39 for i, row := range a {40 d[i] = make([]int8, m)41 for j, x := range row {42 if x != int8(st) {43 d[i][j] = -144 }45 }46 }47 visColor := make([]bool, k)48 visColor[st] = true49 q := slices.Clone(g[st])50 for len(q) > 0 {51 p := q[0]52 q = q[1:]53 curD := d[p.x][p.y]54 c := a[p.x][p.y]55 if !visColor[c] {56 visColor[c] = true57 for _, p2 := range g[c] {58 if d[p2.x][p2.y] < 0 {59 d[p2.x][p2.y] = curD + 160 q = append(q, p2)61 }62 }63 }64 for _, dir := range dir4 {65 x, y := p.x+dir.x, p.y+dir.y66 if 0 <= x && x < n && 0 <= y && y < m && d[x][y] < 0 {67 d[x][y] = curD + 168 q = append(q, pair{x, y})69 }70 }71 }72 dis[st] = d73 }74 75 var q, r1, c1, r2, c2 int76 for Fscan(in, &q); q > 0; q-- {77 Fscan(in, &r1, &c1, &r2, &c2)78 ans := abs(r1-r2) + abs(c1-c2)79 for _, d := range dis {80 ans = min(ans, int(d[r1-1][c1-1])+1+int(d[r2-1][c2-1]))81 }82 Fprintln(out, ans)83 }84}85 8687