- 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
- 76 lines of Go from the credited upstream file 271D.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 "bufio"5 . "fmt"6 "index/suffixarray"7 "io"8 "reflect"9 "sort"10 "unsafe"11)12 1314func CF271D(_r io.Reader, out io.Writer) {15 var s, t []byte16 var k, ans int17 Fscan(bufio.NewReader(_r), &s, &t, &k)18 n := len(s)19 sa := *(*[]int32)(unsafe.Pointer(reflect.ValueOf(suffixarray.New(s)).Elem().FieldByName("sa").Field(0).UnsafeAddr()))20 rank := make([]int, n)21 for i := range rank {22 rank[sa[i]] = i23 }24 height := make([]int, n)25 h := 026 for i, rk := range rank {27 if h > 0 {28 h--29 }30 if rk > 0 {31 for j := int(sa[rk-1]); i+h < n && j+h < n && s[i+h] == s[j+h]; h++ {32 }33 }34 height[rk] = h35 }36 37 sum := make([]int, n+1)38 for i, b := range s {39 sum[i+1] = sum[i] + int(t[b-'a']&15^1)40 }41 for i, p := range sa {42 ans += sort.SearchInts(sum[int(p)+height[i]+1:], sum[p]+k+1)43 }44 Fprint(out, ans)45}46 4748func CF271D_trie(_r io.Reader, out io.Writer) {49 in := bufio.NewReader(_r)50 type node struct{ son [26]*node }51 52 var s, t []byte53 var k, ans int54 Fscan(in, &s, &t, &k)55 root := &node{}56 for i := range s {57 o, c := root, 058 for _, b := range s[i:] {59 b -= 'a'60 if t[b] == '0' {61 if c++; c > k {62 break63 }64 }65 if o.son[b] == nil {66 o.son[b] = &node{}67 ans++68 }69 o = o.son[b]70 }71 }72 Fprint(out, ans)73}74 7576