- 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
- 48 lines of Go from the credited upstream file 1902D.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 "sort"8)9 10func cf1902D(in io.Reader, _w io.Writer) {11 out := bufio.NewWriter(_w)12 defer out.Flush()13 type pair struct{ x, y int }14 dirs := []pair{'L': {-1, 0}, 'R': {1, 0}, 'D': {0, -1}, 'U': {0, 1}}15 var n, q, l, r int16 var s string17 Fscan(in, &n, &q, &s)18 pre := make([]pair, n+1)19 pos := map[pair][]int{{}: {0}}20 p := pair{}21 for i, b := range s {22 d := dirs[b]23 p.x += d.x24 p.y += d.y25 pre[i+1] = p26 pos[p] = append(pos[p], i+1)27 }28 29 for ; q > 0; q-- {30 Fscan(in, &p.x, &p.y, &l, &r)31 ps := pos[p]32 if len(ps) > 0 && (ps[0] < l || ps[len(ps)-1] >= r) {33 Fprintln(out, "YES")34 continue35 }36 q := pair{pre[r].x + pre[l-1].x - p.x, pre[r].y + pre[l-1].y - p.y}37 ps = pos[q]38 i := sort.SearchInts(ps, l-1)39 if i < len(ps) && ps[i] <= r {40 Fprintln(out, "YES")41 } else {42 Fprintln(out, "NO")43 }44 }45}46 4748