- 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
- 54 lines of Go from the credited upstream file 1579D.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 "bufio"5 "container/heap"6 . "fmt"7 "io"8)9 1011type pair79 struct{ v, i int }12type hp79 []pair7913 14func (h hp79) Len() int { return len(h) }15func (h hp79) Less(i, j int) bool { return h[i].v > h[j].v }16func (h hp79) Swap(i, j int) { h[i], h[j] = h[j], h[i] }17func (h *hp79) Push(v interface{}) { *h = append(*h, v.(pair79)) }18func (h *hp79) Pop() interface{} { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v }19 20func CF1579D(_r io.Reader, _w io.Writer) {21 in := bufio.NewReader(_r)22 out := bufio.NewWriter(_w)23 defer out.Flush()24 25 var T, n int26 for Fscan(in, &T); T > 0; T-- {27 Fscan(in, &n)28 h := make(hp79, n)29 for i := range h {30 Fscan(in, &h[i].v)31 h[i].i = i + 132 }33 heap.Init(&h)34 ans := [][2]int{}35 for {36 p, q := heap.Pop(&h).(pair79), heap.Pop(&h).(pair79)37 if q.v == 0 {38 break39 }40 ans = append(ans, [2]int{p.i, q.i})41 p.v--42 q.v--43 heap.Push(&h, p)44 heap.Push(&h, q)45 }46 Fprintln(out, len(ans))47 for _, p := range ans {48 Fprintln(out, p[0], p[1])49 }50 }51}52 5354