- 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
- 100 lines of Go from the credited upstream file 963D.go.
- The implementation visibly relies on sequence storage, ordered lookup.
- 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 "io"7 "math"8 "math/bits"9 "slices"10)11 1213const w63 = bits.UintSize14 15type bitset63 []uint16 17func (b bitset63) set(p int) { b[p/w63] |= 1 << (p % w63) }18 19func (b bitset63) rsh(k int) bitset63 {20 if k == 0 {21 return b22 }23 shift, offset := k/w63, k%w6324 n := len(b)25 if shift >= n {26 return make(bitset63, n)27 }28 b = slices.Clone(b)29 lim := n - 1 - shift30 if offset == 0 {31 copy(b, b[shift:])32 } else {33 for i := 0; i < lim; i++ {34 b[i] = b[i+shift]>>offset | b[i+shift+1]<<(w63-offset)35 }36 b[lim] = b[n-1] >> offset37 }38 clear(b[lim+1:])39 return b40}41 42func (b bitset63) and(c bitset63) {43 for i, v := range c {44 b[i] &= v45 }46}47 48func cf963D(in io.Reader, _w io.Writer) {49 out := bufio.NewWriter(_w)50 defer out.Flush()51 var s, t string52 var q, k int53 Fscan(in, &s, &q)54 n := len(s)55 pos := [26]bitset63{}56 for i := range pos {57 pos[i] = make(bitset63, (n+w63-1)/w63)58 }59 for i, b := range s {60 pos[b-'a'].set(i)61 }62 63 match := make(bitset63, (n+w63-1)/w63)64 idx := []int{}65 for range q {66 Fscan(in, &k, &t)67 m := len(t)68 if m+k-1 > n {69 Fprintln(out, -1)70 continue71 }72 73 for i := range match {74 match[i] = math.MaxUint75 }76 for i, b := range t {77 match.and(pos[b-'a'].rsh(i))78 }79 idx = idx[:0]80 ans := int(1e9)81 for i, v := range match {82 for ; v > 0; v &= v - 1 {83 j := i*w63 | bits.TrailingZeros(v)84 idx = append(idx, j)85 if len(idx) >= k {86 ans = min(ans, j-idx[len(idx)-k])87 }88 }89 }90 91 if len(idx) < k {92 Fprintln(out, -1)93 } else {94 Fprintln(out, ans+m)95 }96 }97}98 99100