- 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
- 55 lines of Go from the credited upstream file 1473D.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 CF1473D(_r io.Reader, _w io.Writer) {11 in := bufio.NewReader(_r)12 out := bufio.NewWriter(_w)13 defer out.Flush()14 min := func(a, b int) int {15 if a > b {16 return b17 }18 return a19 }20 max := func(a, b int) int {21 if b > a {22 return b23 }24 return a25 }26 27 var T, n, m, l, r int28 var s string29 for Fscan(in, &T); T > 0; T-- {30 Fscan(in, &n, &m, &s)31 pre := make([]struct{ cur, max, min int }, n+1)32 for i, c := range s {33 pre[i+1].cur = pre[i].cur + int(c&2) - 134 pre[i+1].max = max(pre[i].max, pre[i+1].cur)35 pre[i+1].min = min(pre[i].min, pre[i+1].cur)36 }37 type pair struct{ up, down int }38 suf := make([]pair, n+1)39 var cur, mx, mn int40 for i := n - 1; i >= 0; i-- {41 cur -= int(s[i]&2) - 142 mx = max(mx, cur)43 mn = min(mn, cur)44 suf[i] = pair{mx - cur, mn - cur}45 }46 for ; m > 0; m-- {47 Fscan(in, &l, &r)48 p, s := pre[l-1], suf[r]49 Fprintln(out, max(p.max, p.cur+s.up)-min(p.min, p.cur+s.down)+1)50 }51 }52}53 5455