- 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
- 86 lines of Go from the credited upstream file 123D.go.
- The implementation visibly relies on sequence storage.
- 2 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 "index/suffixarray"7 "io"8 "reflect"9 "unsafe"10)11 1213func CF123D(_r io.Reader, out io.Writer) {14 max := func(a, b int) int {15 if a > b {16 return a17 }18 return b19 }20 var s []byte21 Fscan(bufio.NewReader(_r), &s)22 n := len(s)23 sa := *(*[]int32)(unsafe.Pointer(reflect.ValueOf(suffixarray.New(s)).Elem().FieldByName("sa").Field(0).UnsafeAddr()))24 rank := make([]int, n)25 for i := range rank {26 rank[sa[i]] = i27 }28 height := make([]int, n+1)29 h := 030 for i, ri := range rank {31 if h > 0 {32 h--33 }34 if ri > 0 {35 for j := int(sa[ri-1]); i+h < n && j+h < n && s[i+h] == s[j+h]; h++ {36 }37 }38 height[ri] = h39 }40 41 type pair struct{ v, i int }42 pl := make([]int, n+1)43 st := []pair{{-1, 0}}44 for i, v := range height {45 for {46 if top := st[len(st)-1]; top.v < v {47 pl[i] = top.i48 break49 }50 st = st[:len(st)-1]51 }52 st = append(st, pair{v, i})53 }54 pr := make([]int, n+1)55 st = []pair{{-1, n}}56 for i := n - 1; i >= 0; i-- {57 v := height[i]58 for {59 if top := st[len(st)-1]; top.v < v {60 pr[i] = top.i61 break62 }63 st = st[:len(st)-1]64 }65 st = append(st, pair{v, i})66 }67 68 ans := int64(n) * int64(n+1) / 269 usedSt := []int{0}70 for i, v := range height {71 for v < usedSt[len(usedSt)-1] {72 usedSt = usedSt[:len(usedSt)-1]73 }74 if v == usedSt[len(usedSt)-1] {75 continue76 }77 usedSt = append(usedSt, v)78 l, r := pl[i], pr[i]79 h, w := int64(v-max(height[l], height[r])), int64(r-l)80 ans += h * w * (w - 1) / 281 }82 Fprint(out, ans)83}84 8586