- 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 1824B2.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 mod24 = 1_000_000_00711 12func pow24(x int64, n int) (res int64) {13 x %= mod2414 res = 115 for ; n > 0; n >>= 1 {16 if n&1 > 0 {17 res = res * x % mod2418 }19 x = x * x % mod2420 }21 return22}23 24type comb24 struct{ _f, _invF []int64 }25 26func newComb24(mx int) *comb24 {27 c := &comb24{[]int64{1}, []int64{1}}28 c._init(mx)29 return c30}31 32func (c *comb24) _init(mx int) {33 n := len(c._f)34 c._f = append(make([]int64, 0, mx+1), c._f...)[:mx+1]35 for i := n; i <= mx; i++ {36 c._f[i] = c._f[i-1] * int64(i) % mod2437 }38 c._invF = append(make([]int64, 0, mx+1), c._invF...)[:mx+1]39 c._invF[mx] = pow24(c._f[mx], mod24-2)40 for i := mx; i > n; i-- {41 c._invF[i-1] = c._invF[i] * int64(i) % mod2442 }43}44 45func (c *comb24) f(n int) int64 {46 if n >= len(c._f) {47 c._init(n * 2)48 }49 return c._f[n]50}51 52func (c *comb24) invF(n int) int64 {53 if n >= len(c._f) {54 c._init(n * 2)55 }56 return c._invF[n]57}58 59func (c *comb24) c(n, k int) int64 {60 if k < 0 || k > n {61 return 062 }63 return c.f(n) * c.invF(k) % mod24 * c.invF(n-k) % mod2464}65 66func CF1824B2(_r io.Reader, out io.Writer) {67 in := bufio.NewReader(_r)68 var n, k, v, w int69 Fscan(in, &n, &k)70 if k%2 > 0 {71 Fprint(out, 1)72 return73 }74 cm := newComb24(0)75 g := make([][]int, n)76 for i := 1; i < n; i++ {77 Fscan(in, &v, &w)78 v--79 w--80 g[v] = append(g[v], w)81 g[w] = append(g[w], v)82 }83 ans := int64(0)84 var f func(int, int) int85 f = func(v, fa int) int {86 sz := 187 for _, w := range g[v] {88 if w != fa {89 sz += f(w, v)90 }91 }92 ans = (ans + cm.c(sz, k/2)*cm.c(n-sz, k/2)) % mod2493 return sz94 }95 f(0, -1)96 Fprint(out, (ans*pow24(cm.c(n, k), mod24-2)+1)%mod24)97}98 99100