- 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
- 106 lines of Go from the credited upstream file 444C.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 cf444C(in io.Reader, _w io.Writer) {12 out := bufio.NewWriter(_w)13 defer out.Flush()14 abs := func(x int) int {15 if x < 0 {16 return -x17 }18 return x19 }20 var n, m, op, l, r, v int21 Fscan(in, &n, &m)22 a := make([]int, n)23 c := make([]int, n)24 for i := range c {25 c[i] = i + 126 }27 28 B := int(math.Sqrt(float64(n)))29 type block struct{ l, r, sum, c, todo int }30 bs := make([]block, (n-1)/B+1)31 for i := 0; i < n; i += B {32 bs[i/B] = block{l: i, r: min(i+B, n)}33 }34 spread := func(b *block) {35 if b.todo > 0 {36 for j := b.l; j < b.r; j++ {37 a[j] += b.todo38 c[j] = b.c39 }40 }41 b.todo = 042 b.c = 043 }44 update := func(l, r, v int) (s int) {45 for j := l; j < r; j++ {46 d := abs(v - c[j])47 c[j] = v48 a[j] += d49 s += d50 }51 return52 }53 54 for range m {55 Fscan(in, &op, &l, &r)56 l--57 if op == 1 {58 Fscan(in, &v)59 for i := range bs {60 b := &bs[i]61 if b.r <= l {62 continue63 }64 if b.l >= r {65 break66 }67 if l <= b.l && b.r <= r {68 if b.c > 0 {69 d := abs(v - b.c)70 b.sum += d * (b.r - b.l)71 b.todo += d72 } else {73 b.sum += update(b.l, b.r, v)74 }75 b.c = v76 } else {77 spread(b)78 b.sum += update(max(b.l, l), min(b.r, r), v)79 }80 }81 } else {82 ans := 083 for i := range bs {84 b := &bs[i]85 if b.r <= l {86 continue87 }88 if b.l >= r {89 break90 }91 if l <= b.l && b.r <= r {92 ans += b.sum93 } else {94 spread(b)95 for j := max(b.l, l); j < min(b.r, r); j++ {96 ans += a[j]97 }98 }99 }100 Fprintln(out, ans)101 }102 }103}104 105106