- 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
- 89 lines of Go from the credited upstream file 802I.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 CF802I(_r io.Reader, out io.Writer) {14 in := bufio.NewReader(_r)15 max := func(a, b int) int {16 if a > b {17 return a18 }19 return b20 }21 var t int22 var s []byte23 for Fscan(in, &t); t > 0; t-- {24 Fscan(in, &s)25 n := len(s)26 sa := *(*[]int32)(unsafe.Pointer(reflect.ValueOf(suffixarray.New(s)).Elem().FieldByName("sa").Field(0).UnsafeAddr()))27 rank := make([]int, n)28 for i := range rank {29 rank[sa[i]] = i30 }31 height := make([]int, n+1)32 h := 033 for i, ri := range rank {34 if h > 0 {35 h--36 }37 if ri > 0 {38 for j := int(sa[ri-1]); i+h < n && j+h < n && s[i+h] == s[j+h]; h++ {39 }40 }41 height[ri] = h42 }43 44 type pair struct{ v, i int }45 pl := make([]int, n+1)46 st := []pair{{-1, 0}}47 for i, v := range height {48 for {49 if top := st[len(st)-1]; top.v < v {50 pl[i] = top.i51 break52 }53 st = st[:len(st)-1]54 }55 st = append(st, pair{v, i})56 }57 pr := make([]int, n+1)58 st = []pair{{-1, n}}59 for i := n - 1; i >= 0; i-- {60 v := height[i]61 for {62 if top := st[len(st)-1]; top.v < v {63 pr[i] = top.i64 break65 }66 st = st[:len(st)-1]67 }68 st = append(st, pair{v, i})69 }70 71 ans := int64(n) * int64(n+1) / 272 usedSt := []int{0}73 for i, v := range height {74 for v < usedSt[len(usedSt)-1] {75 usedSt = usedSt[:len(usedSt)-1]76 }77 if v == usedSt[len(usedSt)-1] {78 continue79 }80 usedSt = append(usedSt, v)81 l, r := pl[i], pr[i]82 h, w := int64(v-max(height[l], height[r])), int64(r-l)83 ans += h * w * (w - 1)84 }85 Fprintln(out, ans)86 }87}88 89