- 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
- 53 lines of Go from the credited upstream file 520E.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 CF520E(_r io.Reader, out io.Writer) {11 in := bufio.NewReader(_r)12 const mod int64 = 1e9 + 713 const mx int = 1e514 F := [mx + 1]int64{1}15 for i := 1; i <= mx; i++ {16 F[i] = F[i-1] * int64(i) % mod17 }18 pow := func(x, n int64) (res int64) {19 res = 120 for ; n > 0; n >>= 1 {21 if n&1 > 0 {22 res = res * x % mod23 }24 x = x * x % mod25 }26 return res27 }28 invF := [...]int64{mx: pow(F[mx], mod-2)}29 for i := mx; i > 0; i-- {30 invF[i-1] = invF[i] * int64(i) % mod31 }32 C := func(n, k int) int64 { return F[n] * invF[k] % mod * invF[n-k] % mod }33 34 var n, k int35 var s string36 Fscan(in, &n, &k, &s)37 sum := make([]int64, n+1)38 for i, b := range s {39 sum[i+1] = sum[i] + int64(b&15)40 }41 ans := int64(0)42 for i, p10 := 0, int64(1); i < n-k; i++ { 43 if k > 0 {44 ans = (ans + sum[n-i-1]*p10%mod*C(n-i-2, k-1)) % mod45 }46 ans = (ans + (sum[n-i]-sum[n-i-1])*p10%mod*C(n-i-1, k)) % mod 47 p10 = p10 * 10 % mod48 }49 Fprint(out, ans)50}51 5253