- 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
- 75 lines of Go from the credited upstream file 615C.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 CF615C(_r io.Reader, _w io.Writer) {11 in := bufio.NewReader(_r)12 out := bufio.NewWriter(_w)13 defer out.Flush()14 15 f := func(text, pattern []byte) (mx, end int) {16 lenP := len(pattern)17 match := make([]int, lenP)18 for i, c := 1, 0; i < lenP; i++ {19 v := pattern[i]20 for c > 0 && pattern[c] != v {21 c = match[c-1]22 }23 if pattern[c] == v {24 c++25 }26 match[i] = c27 }28 c := 029 for i, v := range text {30 for c > 0 && pattern[c] != v {31 c = match[c-1]32 }33 if pattern[c] == v {34 if c++; c > mx {35 mx, end = c, i36 }37 }38 if c == lenP {39 return40 }41 }42 return43 }44 45 var s, t []byte46 Fscan(in, &s, &t)47 n := len(s)48 rev := append([]byte(nil), s...)49 for i := 0; i < n/2; i++ {50 rev[i], rev[n-1-i] = rev[n-1-i], rev[i]51 }52 ans := [][2]int{}53 for len(t) > 0 {54 c1, end1 := f(s, t)55 if c1 == 0 {56 Fprint(out, -1)57 return58 }59 c2, end2 := f(rev, t)60 if c1 >= c2 {61 ans = append(ans, [2]int{end1 - c1 + 2, end1 + 1})62 t = t[c1:]63 } else {64 ans = append(ans, [2]int{n - end2 + c2 - 1, n - end2})65 t = t[c2:]66 }67 }68 Fprintln(out, len(ans))69 for _, p := range ans {70 Fprintln(out, p[0], p[1])71 }72}73 7475