- 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 60E.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 mod60 int10 11type matrix60 [][]int12 13func newMatrix60(n, m int) matrix60 {14 a := make(matrix60, n)15 for i := range a {16 a[i] = make([]int, m)17 }18 return a19}20 21func (a matrix60) mul(b matrix60) matrix60 {22 c := newMatrix60(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) % mod6030 }31 }32 }33 return c34}35 36func (a matrix60) powMul(n int, f0 matrix60) matrix60 {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 cf60E(in io.Reader, out io.Writer) {48 var n, x, y, s0 int49 Fscan(in, &n, &x, &y, &mod60)50 a := make([]int, n)51 for i := range a {52 Fscan(in, &a[i])53 s0 += a[i]54 }55 s0 %= mod6056 if n == 1 {57 Fprint(out, s0)58 return59 }60 61 m := matrix60{{1, 1}, {1, 0}}62 f0 := matrix60{{a[n-1]}, {a[n-2]}}63 big := m.powMul(x, f0)[0][0]64 65 f := func(s0, c, x int) int {66 m := matrix60{{3, 1}, {0, 1}}67 f0 := matrix60{{s0}, {c}}68 return m.powMul(x, f0)[0][0]69 }70 sx := f(s0, -a[0]-a[n-1], x)71 Fprint(out, (f(sx, -a[0]-big, y)+mod60)%mod60)72}73 7475