- 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
- 96 lines of Go from the credited upstream file 1264D2.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 . "fmt"5 "io"6 "slices"7)8 910const mod64 = 99824435311 12func pow64(x, n int) (res int) {13 res = 114 for ; n > 0; n /= 2 {15 if n%2 > 0 {16 res = res * x % mod6417 }18 x = x * x % mod6419 }20 return21}22 23type comb64 struct{ _f, _invF []int }24 25func newComb64(mx int) *comb64 {26 c := &comb64{[]int{1}, []int{1}}27 c._grow(mx)28 return c29}30 31func (c *comb64) _grow(mx int) {32 n := len(c._f)33 c._f = slices.Grow(c._f, mx+1)[:mx+1]34 for i := n; i <= mx; i++ {35 c._f[i] = c._f[i-1] * i % mod6436 }37 c._invF = slices.Grow(c._invF, mx+1)[:mx+1]38 c._invF[mx] = pow64(c._f[mx], mod64-2)39 for i := mx; i > n; i-- {40 c._invF[i-1] = c._invF[i] * i % mod6441 }42}43 44func (c *comb64) f(n int) int {45 if n >= len(c._f) {46 c._grow(n * 2)47 }48 return c._f[n]49}50 51func (c *comb64) invF(n int) int {52 if n >= len(c._f) {53 c._grow(n * 2)54 }55 return c._invF[n]56}57 58func (c *comb64) c(n, k int) int {59 if k < 0 || k > n {60 return 061 }62 return c.f(n) * c.invF(k) % mod64 * c.invF(n-k) % mod6463}64 65func cf1264D2(in io.Reader, out io.Writer) {66 cm := newComb64(0)67 var s string68 var pre, preQ, suf, sufQ, ans int69 Fscan(in, &s)70 71 for _, b := range s {72 if b == ')' {73 suf++74 } else if b == '?' {75 sufQ++76 }77 }78 79 for _, b := range s[:len(s)-1] {80 if b == ')' {81 suf--82 } else if b == '?' {83 sufQ--84 }85 if b == '(' {86 pre++87 } else if b == '?' {88 preQ++89 }90 ans = (ans + preQ*cm.c(preQ+sufQ-1, pre+preQ-suf) + pre*cm.c(preQ+sufQ, pre+preQ-suf)) % mod6491 }92 Fprint(out, ans)93}94 9596