- 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
- 66 lines of Go from the credited upstream file 1572A.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 1112 1314type hp72 struct{ sort.IntSlice }15func (h *hp72) Push(v interface{}) { h.IntSlice = append(h.IntSlice, v.(int)) }16func (h *hp72) Pop() interface{} { a := h.IntSlice; v := a[len(a)-1]; h.IntSlice = a[:len(a)-1]; return v }17 18func CF1572A(_r io.Reader, _w io.Writer) {19 in := bufio.NewReader(_r)20 out := bufio.NewWriter(_w)21 defer out.Flush()22 23 var T, n, v int24 for Fscan(in, &T); T > 0; T-- {25 Fscan(in, &n)26 g := make([][]int, n)27 d := make([]int, n)28 h := hp72{}29 for w := range d {30 Fscan(in, &d[w])31 for i := 0; i < d[w]; i++ {32 Fscan(in, &v)33 g[v-1] = append(g[v-1], w)34 }35 if d[w] == 0 {36 h.IntSlice = append(h.IntSlice, w)37 }38 }39 ans, c := 0, 040 for nxt := []int{}; h.Len() > 0; nxt = nil {41 for h.Len() > 0 {42 c++43 v := heap.Pop(&h).(int)44 for _, w := range g[v] {45 if d[w]--; d[w] == 0 {46 if w > v {47 heap.Push(&h, w)48 } else {49 nxt = append(nxt, w)50 }51 }52 }53 }54 h.IntSlice = nxt55 heap.Init(&h)56 ans++57 }58 if c < n {59 ans = -160 }61 Fprintln(out, ans)62 }63}64 6566