- 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
- 70 lines of Go from the credited upstream file 226C.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 89var mod26 int10 11type matrix26 [][]int12 13func newMatrix26(n, m int) matrix26 {14 a := make(matrix26, n)15 for i := range a {16 a[i] = make([]int, m)17 }18 return a19}20 21func (a matrix26) mul(b matrix26) matrix26 {22 c := newMatrix26(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) % mod2630 }31 }32 }33 return c34}35 36func (a matrix26) powMul(n int, f0 matrix26) matrix26 {37 res := f038 for ; n > 0; n /= 2 {39 if n%2 > 0 {40 res = a.mul(res)41 }42 a = a.mul(a)43 }44 return res45}46 47func cf226C(in io.Reader, out io.Writer) {48 var l, r, k, n int49 Fscan(in, &mod26, &l, &r, &k)50 l--51 for i := 1; i*i <= r; i++ {52 if j := r / i; r/j-l/j >= k {53 n = j54 break55 }56 if r/i-l/i >= k {57 n = i58 }59 }60 m := matrix26{61 {1, 1},62 {1, 0},63 }64 f1 := matrix26{{1}, {0}}65 fn := m.powMul(n-1, f1)66 Fprint(out, fn[0][0]%mod26)67}68 6970