- 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
- 52 lines of Go from the credited upstream file 963A.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 "bufio"5 . "fmt"6 "io"7)8 910func CF963A(_r io.Reader, _w io.Writer) {11 in := bufio.NewReader(_r)12 out := bufio.NewWriter(_w)13 defer out.Flush()14 const mod int64 = 1e9 + 915 pow := func(x int64, n int64) int64 {16 res := int64(1)17 for ; n > 0; n >>= 1 {18 if n&1 == 1 {19 res = res * x % mod20 }21 x = x * x % mod22 }23 return res24 }25 inv := func(a int64) int64 { return pow(a, mod-2) }26 frac := func(a, b int64) int64 { return a * inv(b) % mod }27 28 var n, a, b, k, ans int6429 var s []byte30 Fscan(in, &n, &a, &b, &k, &s)31 q := frac(b, a)32 for i := len(s) - 1; i >= 0; i-- {33 ans *= q34 if s[i] == '+' {35 ans++36 } else {37 ans += mod - 138 }39 ans %= mod40 }41 ans = ans * pow(a, n) % mod42 n = (n + 1) / k43 if q = pow(q, k); q == 1 {44 ans = ans * n % mod45 } else {46 ans = ans * frac(pow(q, n)-1, q-1) % mod47 }48 Fprint(out, ans)49}50 5152