- 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
- 75 lines of Go from the credited upstream file 1906H.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)7 89func cf1906H(in io.Reader, out io.Writer) {10 const mod = 99824435311 pow := func(x, n int) int {12 res := 113 for ; n > 0; n /= 2 {14 if n%2 > 0 {15 res = res * x % mod16 }17 x = x * x % mod18 }19 return res20 }21 const mx int = 2e522 F := [mx + 1]int{1}23 for i := 1; i <= mx; i++ {24 F[i] = F[i-1] * i % mod25 }26 invF := [...]int{mx: pow(F[mx], mod-2)}27 for i := mx; i > 0; i-- {28 invF[i-1] = invF[i] * i % mod29 }30 C := func(n, k int) int {31 return F[n] * invF[k] % mod * invF[n-k] % mod32 }33 34 var n, m int35 var s, t string36 Fscan(in, &n, &m, &s, &t)37 var cntS, cntT [26]int38 for _, b := range s {39 cntS[b-'A']++40 }41 for _, b := range t {42 cntT[b-'A']++43 }44 if cntS[25] > cntT[25] {45 Fprint(out, 0)46 return47 }48 cntT[25] -= cntS[25]49 50 f := make([]int, n+1)51 f[0] = 152 sum := make([]int, n+2)53 for i, cs := range cntS[:25] {54 for j, v := range f {55 sum[j+1] = sum[j] + v56 }57 clear(f)58 for j := max(cs-cntT[i], 0); j <= min(cs, cntT[i+1]); j++ {59 f[j] = sum[min(cntT[i]-cs+j, n)+1] % mod * C(cs, j) % mod60 }61 }62 63 sumF := 064 for _, v := range f {65 sumF += v66 }67 perm := F[n]68 for _, c := range cntS {69 perm = perm * invF[c] % mod70 }71 Fprint(out, sumF%mod*perm%mod)72}73 7475