- 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
- 54 lines of Go from the credited upstream file 494B.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 CF494B(in io.Reader, out io.Writer) {11 const mod int64 = 1e9 + 712 var s, t []byte13 Fscan(bufio.NewReader(in), &s, &t)14 n, m := len(s), len(t)15 match := make([]int, m)16 for i, c := 1, 0; i < m; i++ {17 v := t[i]18 for c > 0 && t[c] != v {19 c = match[c-1]20 }21 if t[c] == v {22 c++23 }24 match[i] = c25 }26 c := 027 sum := make([]int64, n+1)28 iSum := make([]int64, n+1)29 ans := int64(0)30 lastSt := -131 for i, v := range s {32 for c > 0 && t[c] != v {33 c = match[c-1]34 }35 if t[c] == v {36 c++37 }38 if c == m {39 lastSt = i - m + 140 c = match[c-1]41 }42 if lastSt < 0 {43 continue44 }45 res := (int64(lastSt+1) + iSum[lastSt] - sum[lastSt]*int64(n-lastSt)) % mod46 ans += res47 sum[i+1] = (res + sum[i]) % mod48 iSum[i+1] = (res*int64(n-i) + iSum[i]) % mod49 }50 Fprint(out, (ans%mod+mod)%mod)51}52 5354