- 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
- 67 lines of Go from the credited upstream file 965E.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 "container/heap"6 . "fmt"7 "io"8 "sort"9)10 1112type hp65 struct{ sort.IntSlice }13 14func (h hp65) Less(i, j int) bool { return h.IntSlice[i] > h.IntSlice[j] }15func (h *hp65) Push(v interface{}) { h.IntSlice = append(h.IntSlice, v.(int)) }16func (hp65) Pop() (_ interface{}) { return }17 18func CF965E(_r io.Reader, out io.Writer) {19 in := bufio.NewReader(_r)20 type node struct {21 son [26]*node22 end bool23 }24 25 root := &node{end: true}26 hs := map[*node]*hp65{root: {}}27 var n, ans int28 var s []byte29 for Fscan(in, &n); n > 0; n-- {30 Fscan(in, &s)31 ans += len(s)32 o := root33 for _, b := range s {34 b -= 'a'35 if o.son[b] == nil {36 o.son[b] = &node{}37 hs[o.son[b]] = &hp65{}38 }39 o = o.son[b]40 }41 o.end = true42 hs[o].IntSlice = []int{len(s)}43 }44 45 var f func(*node, int)46 f = func(o *node, d int) {47 for _, son := range o.son[:] {48 if son != nil {49 f(son, d+1)50 for _, v := range hs[son].IntSlice {51 heap.Push(hs[o], v)52 }53 }54 }55 if !o.end {56 h := hs[o]57 ans -= h.IntSlice[0] - d58 h.IntSlice[0] = d59 heap.Fix(h, 0)60 }61 }62 f(root, 0)63 Fprint(out, ans)64}65 6667