- 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
- 71 lines of Go from the credited upstream file 25E.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 CF25E(_r io.Reader, out io.Writer) {11 in := bufio.NewReader(_r)12 perm3 := [][]int{{0, 1, 2}, {0, 2, 1}, {1, 0, 2}, {1, 2, 0}, {2, 0, 1}, {2, 1, 0}}13 a := make([]string, 3)14 for i := range a {15 Fscan(in, &a[i])16 }17 18 getMatch := func(s string) []int {19 match := make([]int, len(s))20 for i, c := 1, 0; i < len(s); i++ {21 v := s[i]22 for c > 0 && s[c] != v {23 c = match[c-1]24 }25 if s[c] == v {26 c++27 }28 match[i] = c29 }30 return match31 }32 kmpSearch := func(text, pattern string) bool {33 match := getMatch(pattern)34 lenP := len(pattern)35 c := 036 for _, v := range text {37 for c > 0 && pattern[c] != byte(v) {38 c = match[c-1]39 }40 if pattern[c] == byte(v) {41 c++42 }43 if c == lenP {44 return true45 }46 }47 return false48 }49 merge := func(s, t string) string {50 if kmpSearch(s, t) {51 return s52 }53 if kmpSearch(t, s) {54 return t55 }56 match := getMatch(t + "#" + s)57 return s + t[match[len(match)-1]:]58 }59 60 ans := int(1e9)61 for _, p := range perm3 {62 s := merge(merge(a[p[0]], a[p[1]]), a[p[2]])63 if len(s) < ans {64 ans = len(s)65 }66 }67 Fprint(out, ans)68}69 7071