- 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
- 110 lines of Go from the credited upstream file 750E.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/bits"8)9 1011type mat50 [5][5]int3212 13type seg50 []struct {14 l, r int15 mat5016}17 18func (seg50) merge(a, b mat50) mat50 {19 c := mat50{}20 for i := range 5 {21 for j := i; j < 5; j++ {22 c[i][j] = 1e923 }24 }25 for i := range 5 {26 for k := i; k < 5; k++ {27 if a[i][k] == 1e9 {28 continue29 }30 for j := k; j < 5; j++ {31 c[i][j] = min(c[i][j], a[i][k]+b[k][j])32 }33 }34 }35 return c36}37 38func (t seg50) maintain(o int) {39 t[o].mat50 = t.merge(t[o<<1].mat50, t[o<<1|1].mat50)40}41 42func (t seg50) build(s string, o, l, r int) {43 t[o].l, t[o].r = l, r44 if l == r {45 m := mat50{}46 for i := range 5 {47 for j := i + 1; j < 5; j++ {48 m[i][j] = 1e949 }50 }51 switch s[l] {52 case '2':53 m[0][0] = 154 m[0][1] = 055 case '0':56 m[1][1] = 157 m[1][2] = 058 case '1':59 m[2][2] = 160 m[2][3] = 061 case '7':62 m[3][3] = 163 m[3][4] = 064 case '6':65 m[3][3] = 166 m[4][4] = 167 }68 t[o].mat50 = m69 return70 }71 m := (l + r) >> 172 t.build(s, o<<1, l, m)73 t.build(s, o<<1|1, m+1, r)74 t.maintain(o)75}76 77func (t seg50) query(o, l, r int) mat50 {78 if l <= t[o].l && t[o].r <= r {79 return t[o].mat5080 }81 m := (t[o].l + t[o].r) >> 182 if r <= m {83 return t.query(o<<1, l, r)84 }85 if m < l {86 return t.query(o<<1|1, l, r)87 }88 return t.merge(t.query(o<<1, l, r), t.query(o<<1|1, l, r))89}90 91func cf750E(in io.Reader, _w io.Writer) {92 out := bufio.NewWriter(_w)93 defer out.Flush()94 var n, q, l, r int95 var s string96 Fscan(in, &n, &q, &s)97 t := make(seg50, 2<<bits.Len(uint(n-1)))98 t.build(s, 1, 0, n-1)99 for range q {100 Fscan(in, &l, &r)101 ans := t.query(1, l-1, r-1)[0][4]102 if ans == 1e9 {103 ans = -1104 }105 Fprintln(out, ans)106 }107}108 109110