Approach
Depth-first search
For Codeforces 999E — Reachability from the Capital, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 120 lines of Go from the credited upstream file 999E.go.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
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 CF999E(_r io.Reader, _w io.Writer) {11 in := bufio.NewReader(_r)12 out := bufio.NewWriter(_w)13 defer out.Flush()14 15 var n, m, st int16 Fscan(in, &n, &m, &st)17 st--18 g := make([][]int, n)19 type edge struct{ v, w int }20 _edges := make([]edge, m)21 for i := range _edges {22 var v, w int23 Fscan(in, &v, &w)24 v--25 w--26 _edges[i] = edge{v, w}27 g[v] = append(g[v], w)28 }29 30 vis := make([]bool, n)31 var f func(v int)32 f = func(v int) {33 vis[v] = true34 for _, w := range g[v] {35 if !vis[w] {36 f(w)37 }38 }39 }40 f(st)41 edges := []edge{}42 for _, e := range _edges {43 if !vis[e.v] && !vis[e.w] {44 edges = append(edges, e)45 }46 }47 48 g = make([][]int, n)49 rg := make([][]int, n)50 for _, e := range edges {51 v, w := e.v, e.w52 g[v] = append(g[v], w)53 rg[w] = append(rg[w], v)54 }55 used := make([]bool, n)56 copy(used, vis)57 vs := make([]int, 0, n)58 var dfs func(int)59 dfs = func(v int) {60 used[v] = true61 for _, w := range g[v] {62 if !used[w] {63 dfs(w)64 }65 }66 vs = append(vs, v)67 }68 for v := range g {69 if !used[v] {70 dfs(v)71 }72 }73 74 used = make([]bool, n)75 copy(used, vis)76 var comp []int77 var rdfs func(int)78 rdfs = func(v int) {79 used[v] = true80 comp = append(comp, v)81 for _, w := range rg[v] {82 if !used[w] {83 rdfs(w)84 }85 }86 }87 comps := [][]int{}88 for i := len(vs) - 1; i >= 0; i-- {89 if v := vs[i]; !used[v] {90 comp = []int{}91 rdfs(v)92 comps = append(comps, comp)93 }94 }95 96 sccIDs := make([]int, n)97 for i, cp := range comps {98 for _, v := range cp {99 sccIDs[v] = i100 }101 }102 hasIn := make([]bool, len(comps))103 for _, e := range edges {104 if v, w := sccIDs[e.v], sccIDs[e.w]; v != w {105 hasIn[w] = true106 }107 }108 ans := 0109 for _, has := range hasIn {110 if !has {111 ans++112 }113 }114 Fprint(out, ans)115}116 117118119120