- 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
- 79 lines of Go from the credited upstream file 2009G2.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 cf2009G2(in io.Reader, _w io.Writer) {12 out := bufio.NewWriter(_w)13 defer out.Flush()14 var T, n, k, q int15 for Fscan(in, &T); T > 0; T-- {16 Fscan(in, &n, &k, &q)17 a := make([]int, n)18 for i := range a {19 Fscan(in, &a[i])20 a[i] += n - 2 - i21 }22 23 mn := make([]int, n-k+1)24 cnt := make([]int, n*2-1)25 cc := make([]int, n+1)26 maxC := 027 for r, v := range a {28 cc[cnt[v]]--29 cnt[v]++30 cc[cnt[v]]++31 maxC = max(maxC, cnt[v])32 33 l := r + 1 - k34 if l < 0 {35 continue36 }37 mn[l] = k - maxC38 39 v = a[l]40 cc[cnt[v]]--41 cnt[v]--42 cc[cnt[v]]++43 if cc[maxC] == 0 {44 maxC--45 }46 }47 48 type pair struct{ r, i int }49 qs := make([][]pair, n-k+1)50 for i := range q {51 var l, r int52 Fscan(in, &l, &r)53 qs[l-1] = append(qs[l-1], pair{r - k, i})54 }55 56 ans := make([]int, q)57 type data struct{ r, v, s int }58 st := []data{{len(mn), -1, 0}}59 for i := len(mn) - 1; i >= 0; i-- {60 v := mn[i]61 r := i62 for st[len(st)-1].v >= v {63 r = st[len(st)-1].r64 st = st[:len(st)-1]65 }66 st = append(st, data{r, v, st[len(st)-1].s + (r-i+1)*v})67 for _, p := range qs[i] {68 j := sort.Search(len(st), func(i int) bool { return st[i].r < p.r }) - 169 ans[p.i] = st[len(st)-1].s - st[j-1].s - (st[j].r-p.r)*st[j].v70 }71 }72 for _, v := range ans {73 Fprintln(out, v)74 }75 }76}77 7879