- 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
- 96 lines of Go from the credited upstream file 557E.go.
- The implementation visibly relies on sequence storage.
- 1 loop block 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 "runtime/debug"7)8 910func init() { debug.SetGCPercent(-1) }11 12type node57 struct {13 son [2]*node5714 cnt int15 sum int16}17 18type trie57 struct{ root *node57 }19 20func (t *trie57) put(s []byte, isPal []bool) {21 tot := 022 for _, b := range isPal {23 if b {24 tot++25 }26 }27 o := t.root28 for i, b := range s {29 b -= 'a'30 if o.son[b] == nil {31 o.son[b] = &node57{}32 }33 o = o.son[b]34 o.sum += tot35 if isPal[i] {36 o.cnt++37 tot--38 }39 }40}41 42func (t *trie57) kth(k int) (s []byte) {43 o := t.root44 for {45 for i, son := range o.son {46 if son == nil {47 continue48 }49 if k > son.sum {50 k -= son.sum51 continue52 }53 s = append(s, 'a'+byte(i))54 o = son55 k -= o.cnt56 if k <= 0 {57 return58 }59 break60 }61 }62}63 64func cf557E(in io.Reader, out io.Writer) {65 var s []byte66 var k int67 Fscan(in, &s, &k)68 n := len(s)69 isPal := make([][]bool, n)70 for i := range isPal {71 isPal[i] = make([]bool, n)72 }73 for i := range 2*n - 1 {74 l, r := i/2, (i+1)/275 for l >= 0 && r < n && s[l] == s[r] {76 isPal[l][r] = true77 l -= 278 r += 279 }80 l, r = i/2-1, (i+1)/2+181 for l >= 0 && r < n && s[l] == s[r] {82 isPal[l][r] = true83 l -= 284 r += 285 }86 }87 88 t := &trie57{&node57{}}89 for i, row := range isPal {90 t.put(s[i:], row[i:])91 }92 Fprintf(out, "%s", t.kth(k))93}94 9596