- 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
- 64 lines of Go from the credited upstream file 140C.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 "io"7 . "container/heap"8 "sort"9)10 11type pair140C struct {12 r, cnt int13}14type pairHeap140C []pair140C15 16func (h pairHeap140C) Len() int { return len(h) }17func (h pairHeap140C) Less(i, j int) bool { return h[i].cnt > h[j].cnt }18func (h pairHeap140C) Swap(i, j int) { h[i], h[j] = h[j], h[i] }19func (h *pairHeap140C) Push(v interface{}) { *h = append(*h, v.(pair140C)) }20func (h *pairHeap140C) Pop() (v interface{}) { n := len(*h); *h, v = (*h)[:n-1], (*h)[n-1]; return }21 2223func Sol140C(reader io.Reader, writer io.Writer) {24 in := bufio.NewReader(reader)25 out := bufio.NewWriter(writer)26 defer out.Flush()27 28 rCnt := map[int]int{}29 var n, r int30 for Fscan(in, &n); n > 0; n-- {31 Fscan(in, &r)32 rCnt[r]++33 }34 35 _h := make(pairHeap140C, 0, len(rCnt))36 for r, cnt := range rCnt {37 _h = append(_h, pair140C{r, cnt})38 }39 h := &_h40 Init(h)41 42 ans := [][3]int{}43 for len(_h) >= 3 {44 ps := [3]pair140C{Pop(h).(pair140C), Pop(h).(pair140C), Pop(h).(pair140C)}45 ans = append(ans, [3]int{ps[0].r, ps[1].r, ps[2].r})46 for _, p := range ps {47 p.cnt--48 if p.cnt > 0 {49 Push(h, p)50 }51 }52 }53 Fprintln(out, len(ans))54 for _, rs := range ans {55 balls := rs[:]56 sort.Ints(balls)57 Fprintln(out, balls[2], balls[1], balls[0])58 }59}60 61626364