- 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
- 70 lines of Go from the credited upstream file 1062F.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)8 910func CF1062F(_r io.Reader, out io.Writer) {11 in := bufio.NewReader(_r)12 var n, m, v, w, ans int13 Fscan(in, &n, &m)14 g := make([][]int, n)15 deg := make([]int, n)16 rg := make([][]int, n)17 rdeg := make([]int, n)18 for ; m > 0; m-- {19 Fscan(in, &v, &w)20 v--21 w--22 g[v] = append(g[v], w)23 deg[w]++24 rg[w] = append(rg[w], v)25 rdeg[v]++26 }27 28 cnt := make([]int, n)29 topo := func(g [][]int, deg []int) {30 cntTo := n31 q := []int{}32 for i, d := range deg {33 if d == 0 {34 q = append(q, i)35 cntTo--36 }37 }38 for len(q) > 0 {39 v, q = q[0], q[1:]40 if len(q) == 0 {41 cnt[v] += cntTo 42 } else if len(q) == 1 { 43 for _, w := range g[q[0]] {44 if deg[w] == 1 { 45 goto o46 }47 }48 cnt[v] += cntTo49 }50 o:51 for _, w := range g[v] {52 if deg[w]--; deg[w] == 0 {53 q = append(q, w)54 cntTo--55 }56 }57 }58 }59 topo(g, deg)60 topo(rg, rdeg)61 for _, c := range cnt {62 if c >= n-2 {63 ans++64 }65 }66 Fprint(out, ans)67}68 6970