- Define precisely what one DP state represents.
- Establish the base cases before transitions are evaluated.
- Process states in dependency order and combine only already-known values.
Code notes
- 81 lines of Go from the credited upstream file 113B.go.
- The implementation visibly relies on sequence storage, cached states.
- No explicit loop blocks detected.
Complexity
Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.
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 node13 struct {10 son [26]uint3211 end bool12}13var memo13 = [2e6]node13{{}}14 15func cf113B(in io.Reader, out io.Writer) {16 calcPi := func(s []byte) []int {17 pi := make([]int, len(s))18 match := 019 for i := 1; i < len(pi); i++ {20 v := s[i]21 for match > 0 && s[match] != v {22 match = pi[match-1]23 }24 if s[match] == v {25 match++26 }27 pi[i] = match28 }29 return pi30 }31 kmpSearch := func(text, pattern []byte) (end []int) {32 pi := calcPi(pattern)33 match := 034 for i := range text {35 v := text[i]36 for match > 0 && pattern[match] != v {37 match = pi[match-1]38 }39 if pattern[match] == v {40 match++41 }42 if match == len(pi) {43 end = append(end, i)44 match = pi[match-1]45 }46 }47 return48 }49 50 var s, p, q []byte51 Fscan(in, &s, &p, &q)52 sufEnd := make([]bool, len(s))53 for _, i := range kmpSearch(s, q) {54 sufEnd[i] = true55 }56 57 ans := 058 nodes := memo13[:1]59 root := uint32(0)60 mn := max(len(p), len(q)) - 161 for _, i := range kmpSearch(s, p) {62 i -= len(p) - 163 o := root64 for j, b := range s[i:] {65 b -= 'a'66 if nodes[o].son[b] == 0 {67 nodes[o].son[b] = uint32(len(nodes))68 nodes = append(nodes, node13{})69 }70 o = nodes[o].son[b]71 if j >= mn && sufEnd[i+j] && !nodes[o].end {72 nodes[o].end = true73 ans++74 }75 }76 }77 Fprint(out, ans)78}79 8081