- 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
- 67 lines of Go from the credited upstream file 17E.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 cf17E(in io.Reader, out io.Writer) {10 const mod = 5112398711 var n, tot int12 var s []byte13 Fscan(in, &n, &s)14 t := append(make([]byte, 0, n*2+3), '^')15 for _, c := range s {16 t = append(t, '#', c)17 }18 t = append(t, '#', '$')19 halfLen := make([]int, len(t)-2)20 halfLen[1] = 121 boxM, boxR := 0, 022 for i := 2; i < len(halfLen); i++ {23 hl := 124 if i < boxR {25 hl = min(halfLen[boxM*2-i], boxR-i)26 }27 for t[i-hl] == t[i+hl] {28 hl++29 boxM, boxR = i, i+hl30 }31 halfLen[i] = hl32 tot += hl / 233 }34 tot %= mod35 ans := tot * (tot - 1) / 236 37 diff := make([]int, n+1)38 for i, hl := range halfLen {39 l, r := (i-hl)/2, (i+hl)/2-240 if l <= r {41 diff[(l+r+1)/2]++42 diff[r+1]--43 }44 }45 cntEnd := diff[:n]46 for i := 1; i < n; i++ {47 cntEnd[i] += cntEnd[i-1]48 }49 for i := 1; i < n; i++ {50 cntEnd[i] += cntEnd[i-1]51 }52 53 sum := make([]int, n+1)54 for i, v := range cntEnd {55 sum[i+1] = (sum[i] + v) % mod56 }57 for i, hl := range halfLen {58 l, r := (i-hl)/2, (i+hl)/2-259 if l <= r {60 ans -= sum[(l+r)/2] - sum[max(l-1, 0)]61 }62 }63 Fprint(out, (ans%mod+mod)%mod)64}65 6667