- 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
- 93 lines of Go from the credited upstream file 551E.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 "math"8)9 1011func cf551E(in io.Reader, _w io.Writer) {12 out := bufio.NewWriter(_w)13 defer out.Flush()14 var n, q, op, l, r, v int15 Fscan(in, &n, &q)16 a := make([]int, n)17 for i := range a {18 Fscan(in, &a[i])19 }20 21 type block struct {22 l, r, todo int23 lp, rp map[int]int24 }25 blockSize := int(math.Ceil(math.Sqrt(float64(n) / 5)))26 blocks := make([]*block, (n-1)/blockSize+1)27 calc := func(l, r int) (map[int]int, map[int]int) {28 lp := map[int]int{}29 for j := r - 1; j >= l; j-- {30 lp[a[j]] = j31 }32 rp := map[int]int{}33 for j := l; j < r; j++ {34 rp[a[j]] = j35 }36 return lp, rp37 }38 for i := 0; i < n; i += blockSize {39 r := min(i+blockSize, n)40 lp, rp := calc(i, r)41 blocks[i/blockSize] = &block{i, r, 0, lp, rp}42 }43 44 for range q {45 Fscan(in, &op, &l)46 if op == 1 {47 Fscan(in, &r, &v)48 l--49 for _, b := range blocks {50 if b.r <= l {51 continue52 }53 if b.l >= r {54 break55 }56 if l <= b.l && b.r <= r {57 b.todo += v58 continue59 }60 for j := b.l; j < b.r; j++ {61 a[j] += b.todo62 if l <= j && j < r {63 a[j] += v64 }65 }66 b.todo = 067 b.lp, b.rp = calc(b.l, b.r)68 }69 } else {70 posL := n71 for _, b := range blocks {72 if i, ok := b.lp[l-b.todo]; ok {73 posL = i74 break75 }76 }77 if posL == n {78 Fprintln(out, -1)79 continue80 }81 for i := len(blocks) - 1; ; i-- {82 b := blocks[i]83 if j, ok := b.rp[l-b.todo]; ok {84 Fprintln(out, j-posL)85 break86 }87 }88 }89 }90}91 9293