- 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
- 57 lines of Go from the credited upstream file 1238E.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 "math/bits"8)9 1011func CF1238E(in io.Reader, out io.Writer) {12 min := func(a, b int) int {13 if a > b {14 return b15 }16 return a17 }18 var n, m int19 var s []byte20 Fscan(bufio.NewReader(in), &n, &m, &s)21 cnt := make([][]int, m)22 for i := range cnt {23 cnt[i] = make([]int, m)24 }25 cntAll := make([]int, m)26 for i := 1; i < n; i++ {27 x, y := s[i-1]-'a', s[i]-'a'28 if x != y {29 cnt[x][y]++30 cnt[y][x]++31 cntAll[x]++32 cntAll[y]++33 }34 }35 36 f := make([]int, 1<<m)37 for i := 1; i < len(f); i++ {38 f[i] = 1e939 }40 for s, dv := range f {41 i := bits.OnesCount(uint(s))42 for cus, lb := len(f)-1^s, 0; cus > 0; cus ^= lb {43 lb = cus & -cus44 ns := s | lb45 p := bits.TrailingZeros(uint(lb))46 sum := 047 for _s := uint(s); _s > 0; _s &= _s - 1 {48 sum += cnt[p][bits.TrailingZeros(_s)]49 }50 f[ns] = min(f[ns], dv+(sum*2-cntAll[p])*i)51 }52 }53 Fprint(out, f[len(f)-1])54}55 5657