- 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
- 72 lines of Go from the credited upstream file 1295B.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 CF1295B(_r io.Reader, _w io.Writer) {11 in := bufio.NewReader(_r)12 out := bufio.NewWriter(_w)13 defer out.Flush()14 moveToRange := func(st, d, l, r int) (firstPos int, ok bool) {15 switch {16 case st < l:17 if d < 0 {18 return19 }20 return l + ((st-l)%d+d)%d, true21 case st <= r:22 return st, true23 default:24 if d > 0 {25 return26 }27 return r + ((st-r)%d+d)%d, true28 }29 }30 31 var t, n, x int32 var s []byte33 solve := func() (ans int) {34 cnts := map[int]int{0: 1}35 d, l, r := 0, 0, 036 for i, b := range s {37 if b == '0' {38 d++39 if d > r {40 r = d41 }42 } else {43 d--44 if d < l {45 l = d46 }47 }48 if i+1 < n {49 cnts[d]++50 }51 }52 if d == 0 {53 if c, ok := cnts[x]; ok && c > 0 {54 return -155 }56 } else if x, ok := moveToRange(x, -d, l, r); ok {57 for ; x >= l && x <= r; x -= d {58 ans += cnts[x]59 }60 }61 return62 }63 for Fscan(in, &t); t > 0; t-- {64 Fscan(in, &n, &x, &s)65 Fprintln(out, solve())66 }67}68 69707172