- 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
- 65 lines of Go from the credited upstream file 1182E.go.
- The implementation keeps its working state in language-native values and containers.
- 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 89type matrix82 [3][3]int6410 11func (a matrix82) mul(b matrix82) (c matrix82) {12 const mod = 1_000_000_00713 for i, r := range a {14 for j := range b[0] {15 for k, v := range r {16 c[i][j] = (c[i][j] + v*b[k][j]) % (mod - 1)17 }18 }19 }20 return21}22 23func (a matrix82) pow(n int64) (res matrix82) {24 for i := range res {25 res[i][i] = 126 }27 for ; n > 0; n >>= 1 {28 if n&1 > 0 {29 res = res.mul(a)30 }31 a = a.mul(a)32 }33 return34}35 36func CF1182E(in io.Reader, out io.Writer) {37 const mod = 1_000_000_00738 pow := func(x, n int64) (res int64) {39 res = 140 for ; n > 0; n >>= 1 {41 if n&1 > 0 {42 res = res * x % mod43 }44 x = x * x % mod45 }46 return47 }48 var n, f1, f2, f3, c int6449 Fscan(in, &n, &f1, &f2, &f3, &c)50 f1 = f1 * c % mod51 f2 = f2 * c % mod * c % mod52 f3 = f3 * c % mod * c % mod * c % mod53 m := matrix82{54 {1, 1, 1},55 {1, 0, 0},56 {0, 1, 0},57 }.pow(n - 3)58 Fprint(out, pow(c, mod-1-n%(mod-1))*59 pow(f3, m[0][0])%mod*60 pow(f2, m[0][1])%mod*61 pow(f1, m[0][2])%mod)62}63 6465