- 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
- 100 lines of Go from the credited upstream file 1931G.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 910const mod31 = 99824435311 12func pow31(x, n int) (res int) {13 x %= mod3114 res = 115 for ; n > 0; n /= 2 {16 if n%2 > 0 {17 res = res * x % mod3118 }19 x = x * x % mod3120 }21 return22}23 24type comb31 struct{ _f, _invF []int }25 26func newComb31(mx int) *comb31 {27 c := &comb31{[]int{1}, []int{1}}28 c._grow(mx)29 return c30}31 32func (c *comb31) _grow(mx int) {33 n := len(c._f)34 c._f = append(make([]int, 0, mx+1), c._f...)[:mx+1]35 for i := n; i <= mx; i++ {36 c._f[i] = c._f[i-1] * i % mod3137 }38 c._invF = append(make([]int, 0, mx+1), c._invF...)[:mx+1]39 c._invF[mx] = pow31(c._f[mx], mod31-2)40 for i := mx; i > n; i-- {41 c._invF[i-1] = c._invF[i] * i % mod3142 }43}44 45func (c *comb31) f(n int) int {46 if n >= len(c._f) {47 c._grow(n * 2)48 }49 return c._f[n]50}51 52func (c *comb31) invF(n int) int {53 if n >= len(c._f) {54 c._grow(n * 2)55 }56 return c._invF[n]57}58 59func (c *comb31) c(n, k int) int {60 if k < 0 || k > n {61 return 062 }63 return c.f(n) * c.invF(k) % mod31 * c.invF(n-k) % mod3164}65 6667func (c *comb31) h(box, ball int) int {68 return c.c(box+ball-1, ball)69}70 71func cf1931G(_r io.Reader, _w io.Writer) {72 in := bufio.NewReader(_r)73 out := bufio.NewWriter(_w)74 defer out.Flush()75 cm := newComb31(0)76 77 var T, a, b, c, d int78 for Fscan(in, &T); T > 0; T-- {79 Fscan(in, &a, &b, &c, &d)80 if a > b {81 a, b = b, a82 }83 if b-a > 1 {84 Fprintln(out, 0)85 } else if b == 0 {86 if c > 0 && d > 0 {87 Fprintln(out, 0)88 } else {89 Fprintln(out, 1)90 }91 } else if a == b {92 Fprintln(out, (cm.h(b, c)*cm.h(b+1, d)+cm.h(b+1, c)*cm.h(b, d))%mod31)93 } else {94 Fprintln(out, cm.h(b, c)*cm.h(b, d)%mod31)95 }96 }97}98 99100