- 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 1404C.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 1011func CF1404C(_r io.Reader, _w io.Writer) {12 in := bufio.NewReader(_r)13 out := bufio.NewWriter(_w)14 defer out.Flush()15 min := func(a, b int) int {16 if a < b {17 return a18 }19 return b20 }21 22 var n, q int23 Fscan(in, &n, &q)24 a := make([]int, n+1)25 for i := 1; i <= n; i++ {26 Fscan(in, &a[i])27 a[i] = i - a[i]28 }29 qs := make([]struct{ l, r, i int }, q)30 for i := range qs {31 Fscan(in, &qs[i].l, &qs[i].r)32 qs[i].l++33 qs[i].r = n - qs[i].r34 qs[i].i = i35 }36 sort.Slice(qs, func(i, j int) bool { return qs[i].r < qs[j].r })37 38 ans := make([]int, q)39 tree := make([]int, n+2)40 kth := func(k int) (res int) {41 for b := 1 << 18; b > 0; b >>= 1 {42 if next := res | b; next <= n && k > tree[next] {43 k -= tree[next]44 res = next45 }46 }47 return res + 148 }49 cur := 150 for _, q := range qs {51 for ; cur <= q.r; cur++ {52 k := 153 if a[cur] >= 0 {54 k = min(kth(cur-a[cur]), cur+1)55 }56 for ; k <= n; k += k & -k {57 tree[k]++58 }59 }60 s := 061 for i := q.l; i > 0; i &= i - 1 {62 s += tree[i]63 }64 ans[q.i] = q.r - s65 }66 for _, v := range ans {67 Fprintln(out, v)68 }69}70 7172