- 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
- 83 lines of Go from the credited upstream file 222E.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 89const mod22 = 1_000_000_00710 11type matrix22 [][]int12 13func newMatrix22(n, m int) matrix22 {14 a := make(matrix22, n)15 for i := range a {16 a[i] = make([]int, m)17 }18 return a19}20 21func (a matrix22) mul(b matrix22) matrix22 {22 c := newMatrix22(len(a), len(b[0]))23 for i, row := range a {24 for k, x := range row {25 if x == 0 {26 continue27 }28 for j, y := range b[k] {29 c[i][j] = (c[i][j] + x*y) % mod2230 }31 }32 }33 return c34}35 3637func (a matrix22) powMul(n int, f1 matrix22) matrix22 {38 res := f139 for ; n > 0; n /= 2 {40 if n%2 > 0 {41 res = a.mul(res)42 }43 a = a.mul(a)44 }45 return res46}47 48func cf222E(in io.Reader, out io.Writer) {49 var n, sz, k, ans int50 var s string51 Fscan(in, &n, &sz, &k)52 f := func(b byte) byte {53 if b >= 'a' {54 return b - 'a'55 }56 return b - 'A' + 2657 }58 59 m := newMatrix22(sz, sz)60 for i := range m {61 for j := range m[i] {62 m[i][j] = 163 }64 }65 for range k {66 Fscan(in, &s)67 m[f(s[1])][f(s[0])] = 068 }69 70 f1 := newMatrix22(sz, 1)71 for i := range f1 {72 f1[i][0] = 173 }74 75 fn := m.powMul(n-1, f1)76 for _, row := range fn {77 ans += row[0]78 }79 Fprint(out, ans%mod22)80}81 8283