- 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
- 105 lines of Go from the credited upstream file 1608D.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 mod08 = 99824435311 12func pow08(x, n int) (res int) {13 res = 114 for ; n > 0; n /= 2 {15 if n%2 > 0 {16 res = res * x % mod0817 }18 x = x * x % mod0819 }20 return21}22 23type comb08 struct{ _f, _invF []int }24 25func newComb08(mx int) *comb08 {26 c := &comb08{[]int{1}, []int{1}}27 c._grow(mx)28 return c29}30 31func (c *comb08) _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 % mod0836 }37 c._invF = slices.Grow(c._invF, mx+1)[:mx+1]38 c._invF[mx] = pow08(c._f[mx], mod08-2)39 for i := mx; i > n; i-- {40 c._invF[i-1] = c._invF[i] * i % mod0841 }42}43 44func (c *comb08) 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 *comb08) 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 *comb08) c(n, k int) int {59 if k < 0 || k > n {60 return 061 }62 return c.f(n) * c.invF(k) % mod08 * c.invF(n-k) % mod0863}64 65func cf1608D(in io.Reader, out io.Writer) {66 cm := newComb08(0)67 var n, q, w int68 var s string69 bad, allBW, allWB := 1, 1, 170 Fscan(in, &n)71 for range n {72 Fscan(in, &s)73 u, v := s[0], s[1]74 if u == 'W' {75 w++76 } else if u == '?' {77 q++78 }79 if v == 'W' {80 w++81 } else if v == '?' {82 q++83 }84 85 86 if u == '?' && v == '?' {87 bad = bad * 2 % mod08 88 } else if u == v {89 90 91 bad = 092 }93 if u == 'W' || v == 'B' {94 allBW = 095 }96 if u == 'B' || v == 'W' {97 allWB = 098 }99 }100 101 Fprint(out, (cm.c(q, n-w)-bad+allBW+allWB+mod08)%mod08)102}103 104105