- 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
- 72 lines of Go from the credited upstream file 380C.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 910type data80 struct{ lc, rc int }11type seg80 []struct {12 l, r int13 data8014}15 16func (t seg80) do(l, r data80) data80 {17 min := l.lc18 if r.rc < min {19 min = r.rc20 }21 return data80{l.lc + r.lc - min, l.rc + r.rc - min}22}23 24func (t seg80) build(s string, o, l, r int) {25 t[o].l, t[o].r = l, r26 if l == r {27 if s[l-1] == '(' {28 t[o].lc = 129 } else {30 t[o].rc = 131 }32 return33 }34 m := (l + r) >> 135 t.build(s, o<<1, l, m)36 t.build(s, o<<1|1, m+1, r)37 t[o].data80 = t.do(t[o<<1].data80, t[o<<1|1].data80)38}39 40func (t seg80) query(o, l, r int) data80 {41 if l <= t[o].l && t[o].r <= r {42 return t[o].data8043 }44 m := (t[o].l + t[o].r) >> 145 if r <= m {46 return t.query(o<<1, l, r)47 }48 if l > m {49 return t.query(o<<1|1, l, r)50 }51 return t.do(t.query(o<<1, l, r), t.query(o<<1|1, l, r))52}53 54func CF380C(_r io.Reader, _w io.Writer) {55 in := bufio.NewReader(_r)56 out := bufio.NewWriter(_w)57 defer out.Flush()58 59 var s string60 Fscan(in, &s)61 t := make(seg80, 4*len(s))62 t.build(s, 1, 1, len(s))63 var q, l, r int64 for Fscan(in, &q); q > 0; q-- {65 Fscan(in, &l, &r)66 d := t.query(1, l, r)67 Fprintln(out, r-l+1-d.lc-d.rc)68 }69}70 7172