- 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
- 55 lines of Go from the credited upstream file 17C.go.
- The implementation keeps its working state in language-native values and containers.
- 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 . "fmt"5 "io"6)7 89func cf17C(in io.Reader, out io.Writer) {10 abs := func(x int) int {11 if x < 0 {12 return -x13 }14 return x15 }16 const mod = 5112398717 const maxN = 15218 const maxM = 5219 var n int20 var s string21 Fscan(in, &n, &s)22 s = " " + s23 t := [3][maxN]int32{}24 for x := n; x >= 1; x-- {25 for y := range 3 {26 t[y][x] = t[y][x+1]27 }28 t[s[x]-'a'][x] = int32(x)29 }30 31 f := [maxN][maxM][maxM][maxM]int32{}32 f[1][0][0][0] = 133 ans := int32(0)34 lim := (n + 2) / 335 for l := 1; l <= n; l++ {36 for x := range lim + 1 {37 for y := range lim + 1 {38 for z := range lim + 1 {39 c := f[l][x][y][z]40 f[t[0][l]][x+1][y][z] = (f[t[0][l]][x+1][y][z] + c) % mod41 f[t[1][l]][x][y+1][z] = (f[t[1][l]][x][y+1][z] + c) % mod42 f[t[2][l]][x][y][z+1] = (f[t[2][l]][x][y][z+1] + c) % mod43 if x+y+z == n && abs(x-y) <= 1 && abs(y-z) <= 1 && abs(z-x) <= 1 {44 ans = (ans + c) % mod45 }46 }47 }48 }49 }50 51 Fprintln(out, ans)52}53 5455