- 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
- 99 lines of Go from the credited upstream file 2034F2.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 mod34 = 99824435311 12func pow34(x, n int) int {13 res := 114 for ; n > 0; n /= 2 {15 if n%2 > 0 {16 res = res * x % mod3417 }18 x = x * x % mod3419 }20 return res21}22 23type comb34 struct{ _f, _invF []int }24 25func newComb34(mx int) *comb34 {26 c := &comb34{[]int{1}, []int{1}}27 c._grow(mx)28 return c29}30 31func (c *comb34) _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 % mod3436 }37 c._invF = slices.Grow(c._invF, mx+1)[:mx+1]38 c._invF[mx] = pow34(c._f[mx], mod34-2)39 for i := mx; i > n; i-- {40 c._invF[i-1] = c._invF[i] * i % mod3441 }42}43 44func (c *comb34) 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 *comb34) 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 *comb34) c(n, k int) int {59 if k < 0 || k > n {60 return 061 }62 return c.f(n) * c.invF(k) % mod34 * c.invF(n-k) % mod3463}64 65func cf2034F2(in io.Reader, out io.Writer) {66 cm := newComb34(0)67 var T, n, m, k int68 for Fscan(in, &T); T > 0; T-- {69 Fscan(in, &n, &m, &k)70 type pair struct{ r, b int }71 a := make([]pair, k+1)72 for i := 1; i <= k; i++ {73 Fscan(in, &a[i].r, &a[i].b)74 }75 slices.SortFunc(a[1:], func(x, y pair) int { return x.r + x.b - y.r - y.b })76 77 ans := 078 f := make([]int, k+1)79 f[0] = 180 for i := 1; i <= k; i++ {81 p := a[i]82 for j, q := range a[:i] {83 x := p.r - q.r84 y := p.b - q.b85 if x >= 0 && y >= 0 {86 f[i] = (f[i] + f[j]*cm.c(x+y, x)) % mod3487 }88 }89 nn := n - p.r90 mm := m - p.b91 ans = (ans + f[i]*(nn*2+mm)%mod34*cm.c(nn+mm, nn)) % mod3492 }93 ans = (ans*pow34(cm.c(n+m, n), mod34-2) + n*2 + m) % mod3494 Fprintln(out, ans)95 }96}97 9899