- 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
- 84 lines of Go from the credited upstream file 2140E2.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 "math/bits"7)8 910func cf2140E2(in io.Reader, out io.Writer) {11 const mod = 1_000_000_00712 pow := func(x, n int) int {13 res := 114 for ; n > 0; n /= 2 {15 if n%2 > 0 {16 res = res * x % mod17 }18 x = x * x % mod19 }20 return res21 }22 23 var T, n, m, k int24 for Fscan(in, &T); T > 0; T-- {25 Fscan(in, &n, &m, &k)26 a := make([]int, k)27 for i := range a {28 Fscan(in, &a[i])29 a[i]--30 }31 32 f := make([]byte, 1<<n)33 f[1] = 134 for sz := 2; sz <= n; sz++ {35 if (n-sz)%2 == 0 {36 o:37 for mask := 1<<sz - 1; mask > 0; mask-- {38 for _, i := range a {39 if i >= sz {40 break41 }42 if f[mask>>(i+1)<<i|mask&(1<<i-1)] > 0 {43 f[mask] = 144 continue o45 }46 }47 f[mask] = 048 }49 } else {50 o2:51 for mask := 1<<sz - 1; mask > 0; mask-- {52 for _, i := range a {53 if i >= sz {54 break55 }56 if f[mask>>(i+1)<<i|mask&(1<<i-1)] == 0 {57 f[mask] = 058 continue o259 }60 }61 f[mask] = 162 }63 }64 }65 66 cnt := make([]int, n+1)67 for mask, v := range f {68 cnt[bits.OnesCount(uint(mask))] += int(v)69 }70 71 ans := 072 for i, c := range cnt {73 s := 074 for low := 1; low <= m; low++ {75 s = (s + pow(m-low+1, i)*pow(low-1, n-i)) % mod76 }77 ans += s * c78 }79 Fprintln(out, ans%mod)80 }81}82 8384