- 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
- 88 lines of Go from the credited upstream file 2006D.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 cf2006D(in io.Reader, _w io.Writer) {11 out := bufio.NewWriter(_w)12 defer out.Flush()13 var T, n, q, k int14 for Fscan(in, &T); T > 0; T-- {15 Fscan(in, &n, &q, &k)16 sq := 017 for i := 1; i*i <= k; i++ {18 sq = i19 }20 psum := make([]int, n+1)21 csum := make([]int, q)22 ccnt := make([]int, q)23 l := make([]int, q)24 r := make([]int, q)25 ans := make([]int, q)26 v1 := make([][]int, sq+1)27 v2 := make([][]int, sq+1)28 for i := range n {29 var x int30 Fscan(in, &x)31 if x <= sq {32 v1[x] = append(v1[x], i)33 } else {34 v2[k/x] = append(v2[k/x], i)35 }36 }37 38 for i := range q {39 Fscan(in, &l[i], &r[i])40 l[i]--41 }42 43 for i := 1; i <= sq; i++ {44 clear(psum)45 for _, p := range v1[i] {46 psum[p+1]--47 }48 for _, p := range v2[i] {49 psum[p+1]++50 }51 for j := 1; j <= n; j++ {52 psum[j] += psum[j-1]53 }54 for j := 0; j < q; j++ {55 csum[j] += psum[r[j]]56 csum[j] -= psum[l[j]]57 }58 59 clear(psum)60 for _, p := range v1[i] {61 psum[p+1]++62 }63 for _, p := range v2[i] {64 psum[p+1]++65 }66 for j := 1; j <= n; j++ {67 psum[j] += psum[j-1]68 }69 for j := range q {70 ccnt[j] += psum[r[j]]71 ccnt[j] -= psum[l[j]]72 if ccnt[j] == r[j]-l[j] {73 ans[j] = max(ans[j], csum[j]/2)74 } else {75 ans[j] = max(ans[j], (csum[j]+1)/2)76 }77 }78 }79 80 for _, v := range ans {81 Fprint(out, v, " ")82 }83 Fprintln(out)84 }85}86 8788