- 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
- 104 lines of Go from the credited upstream file 1335F.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 CF1335F(_r io.Reader, _w io.Writer) {11 in := bufio.NewReader(_r)12 out := bufio.NewWriter(_w)13 defer out.Flush()14 dir4 := ['U' + 1]int{'L': -1, 'R': 1}15 type pair struct{ v, d int }16 17 var t, n, m int18 var s string19 for Fscan(in, &t); t > 0; t-- {20 Fscan(in, &n, &m)21 dir4['D'] = m22 dir4['U'] = -m23 c := make([]byte, 0, n*m)24 for i := 0; i < n; i++ {25 Fscan(in, &s)26 c = append(c, s...)27 }28 deg := make([]int8, n*m)29 rg := make([][]int, n*m)30 g := make([]byte, 0, n*m)31 for i := 0; i < n; i++ {32 Fscan(in, &s)33 g = append(g, s...)34 for j, b := range s {35 v := i*m + j36 w := v + dir4[b]37 deg[w]++38 rg[w] = append(rg[w], v)39 }40 }41 42 vis := make([]int8, n*m)43 q := []int{}44 for i, d := range deg {45 if d == 0 {46 q = append(q, i)47 }48 }49 for len(q) > 0 {50 v := q[0]51 q = q[1:]52 vis[v] = 153 v += dir4[g[v]]54 deg[v]--55 if deg[v] == 0 {56 q = append(q, v)57 }58 }59 60 ans1, ans2 := 0, 061 for v, b := range vis {62 if b != 0 {63 continue64 }65 cycle := []int{}66 for ; vis[v] == 0; v += dir4[g[v]] {67 vis[v] = 268 cycle = append(cycle, v)69 }70 sz := len(cycle)71 for i, cv := range cycle {72 for _, r := range rg[cv] {73 if vis[r] == 2 {74 continue75 }76 77 maxDep := 078 for q := []pair{{r, 1}}; len(q) > 0; {79 p := q[0]80 q = q[1:]81 v, d := p.v, p.d82 if d > maxDep && c[v] == '0' {83 c[cycle[((i-d)%sz+sz)%sz]] = '0' 84 maxDep = d85 }86 for _, w := range rg[v] {87 q = append(q, pair{w, d + 1})88 }89 }90 }91 }92 ans1 += sz93 for _, v := range cycle {94 if c[v] == '0' {95 ans2++96 }97 }98 }99 Fprintln(out, ans1, ans2)100 }101}102 103104