- 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
- 66 lines of Go from the credited upstream file 159D.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 . "fmt"5 "io"6)7 89func cf159D(in io.Reader, out io.Writer) {10 var s []byte11 Fscan(in, &s)12 n := len(s)13 t := append(make([]byte, 0, n*2+3), '^')14 for _, c := range s {15 t = append(t, '#', c)16 }17 t = append(t, '#', '$')18 halfLen := make([]int, len(t)-2)19 halfLen[1] = 120 boxM, boxR := 0, 021 for i := 2; i < len(halfLen); i++ {22 hl := 123 if i < boxR {24 hl = min(halfLen[boxM*2-i], boxR-i)25 }26 for t[i-hl] == t[i+hl] {27 hl++28 boxM, boxR = i, i+hl29 }30 halfLen[i] = hl31 }32 33 diff := make([]int, n+1)34 for i, hl := range halfLen {35 l, r := (i-hl)/2, (i+hl)/2-236 if r < l {37 continue38 }39 diff[(l+r+1)/2]++40 diff[r+1]--41 }42 cntEnd := diff[:n]43 for i := 1; i < n; i++ {44 cntEnd[i] += cntEnd[i-1]45 }46 for i := 1; i < n; i++ {47 cntEnd[i] += cntEnd[i-1]48 }49 50 sum := make([]int, n+1)51 for i, v := range cntEnd {52 sum[i+1] = sum[i] + v53 }54 ans := 055 for i, hl := range halfLen {56 l, r := (i-hl)/2, (i+hl)/2-257 if r < l {58 continue59 }60 ans += sum[(l+r)/2] - sum[max(l-1, 0)]61 }62 Fprint(out, ans)63}64 6566